The Network Connection was lost from Alamofire

Viewed 2435

I got this error many times in my project and it very irritates me because I have full internet connectivity though I get this error repeatedly.

enter image description here

What is the solution...?

I am using

Swift - 3.3

Alamofire - 4.7.3

API Calling Code:

class  func post(_ URL: String, withParams params: [String : AnyObject], onView parentView: UIViewController, hnadler completion: @escaping ([AnyHashable: Any]!) -> Void) {
        var URLString  = String()
        URLString = APIConstants.kServerURL + URL
        var headers = [String: String]()
        headers["Content-Type"] = "application/x-www-form-urlencoded"
        
        Alamofire.request(URLString,method: .post, parameters: params , headers : headers)
            .validate(contentType: ["application/vnd.api+json"])
            .responseJSON { response in
                switch response.result {
                case .success( _):
                    var completionVarible = [NSObject : AnyObject]()
                    completionVarible = response.result.value as! [AnyHashable: Any]! as [NSObject : AnyObject]
                    completion(completionVarible)
                case .failure(let error):
                    self.handleFailureResponse(Error: error as NSError?, parentView: parentView)
                }
        }
    }
3 Answers

If the alert appears immediately you may try to change the cache policy to .reloadIgnoringCacheData

I don't know exactly why this error occurs but I have also faced this error, so I have put one solution. This error has some unique error code. So check that error code and ignore alert over there or you can again try this API call if this error code you get.

I find one solution to this issue if you using Alamofire.

First import Alamofire in your common class otherwise you can create a separate class for check internet connection.

import Alamofire

class Connectivity {
    class func isConnectedToInternet() ->Bool {
        return NetworkReachabilityManager()!.isReachable
    }
}

Call below method before you API call

if !Connectivity.isConnectedToInternet() {
            ServiceHandler.ShowAlert(message: "Check your internet connectivity.", title: "Error", parentView: self) //This is my comman method for display alert.
            return
        }
Related