Handle No Internet Connection Error Before Try to Parse the Result in Alamofire

后端 未结 7 1911
旧巷少年郎
旧巷少年郎 2020-12-30 03:04

How should I handle if there is an error occurs when there is no internet connection in Alamofire. I tried checking if data is nil or not but it does not work.

Below

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 03:34

    This works for me in Swift2.x

    Alamofire.request(.POST, url).responseJSON { response in
        switch response.result {
            case .Success(let json):
                // internet works.  
            case .Failure(let error):
    
                if let err = error as? NSURLError where err == .NotConnectedToInternet {
                    // no internet connection
                } else {
                    // other failures
                }
        }
    }
    

提交回复
热议问题