Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 is how I use Alamofire

Alamofire.request(.POST, REGISTER_URL, parameters: parameters, encoding: .JSON, headers: getAuthenticationHeader()).response { (request, response, data, errorType) -> Void in

    let resultObject: APIResults = APIResults(JSONDecoder(data!));
    let responseCode: Int = Int(resultObject.code!)!;// THIS CRASHES WHEN THERE IS NO INTERNET CONNECTION

    if (responseCode == 200) {
        available = true;
    }

    finished = true;

}
like image 921
JayVDiyk Avatar asked Sep 15 '15 07:09

JayVDiyk


3 Answers

Swift 3 Solution

Assuming you have an Error instance you can do the following:

if let err = error as? URLError, err.code  == URLError.Code.notConnectedToInternet
{
    // No internet
}
else
{
    // Other errors
}

You simply cast error into a URLError. This works since URLError implements the Error protocol. Here is a quote from the apple documentation for reference:

URLError: Describes errors in the URL error domain.

Once you have a URLError instance you can simply compare its code property, which is a URLError.Code enum, against the any relevant enum cases (in our example URLError.Code.notConnectedToInternet).

like image 111
arauter Avatar answered Oct 04 '22 00:10

arauter


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
            }
    }
}
like image 31
Melvin Avatar answered Oct 03 '22 22:10

Melvin


I agree with @Shripada. First you should use Reachability to check for connectivity. There is a Swift library here: https://github.com/ashleymills/Reachability.swift

additionally you can use one of the Alamofire validation methods:

Alamofire.request(.POST, REGISTER_URL, parameters: parameters, encoding: .JSON, headers: getAuthenticationHeader()).validate(statusCode: 200 ..< 300).response { (request, response, data, error) -> Void in
    if error != nil {
        println("Server responded with: \(response.statusCode)")
        return
    }

    // Handle your response data here
}
like image 39
ergoon Avatar answered Oct 03 '22 22:10

ergoon