Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire: Network error vs invalid status code?

Using Alamofire 4/Swift 3 how can you differentiate between a request that fails due to:

  1. Network connectivity (host down, can't reach host) vs
  2. Invalid server HTTP response code (ie: 499) which causes the Alamofire request to fail due to calling validate()?

Code:

    sessionManager.request(url, method: .post, parameters:dict, encoding: JSONEncoding.default)
        .validate() //Validate status code
        .responseData { response in

        if response.result.isFailure {
               //??NETWORK ERROR OR INVALID SERVER RESPONSE??
        }
    }

We want to handle each case differently. In the latter case we want to interrogate the response. (In the former we don't as there is no response).

like image 525
Marcus Leon Avatar asked Dec 03 '16 15:12

Marcus Leon


2 Answers

Here's our current working solution:

sessionManager.request(url, method: .post, parameters:dict, encoding: JSONEncoding.default)
    .validate() //Validate status code
    .responseData { response in

    if response.result.isFailure {
        if let error = response.result.error as? AFError, error.responseCode == 499 {
            //INVALID SESSION RESPONSE
        } else {
            //NETWORK FAILURE
        }
    }
}

If result.error it is of type AFError you can use responseCode. From the AFError source comments:

/// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`,
/// `responseContentType`, and `responseCode` properties will contain the associated values.
public var isResponseValidationError: Bool {
    if case .responseValidationFailed = self { return true }
    return false
}

Maybe there is a better way (?) but that seems to work...

like image 157
Marcus Leon Avatar answered Oct 11 '22 03:10

Marcus Leon


Alamofire can tell you about the status of the request, this code works just fine for me:

if let error = response.result.error as? NSError {
    print(error)//print the error description
    if (error.code == -1009){
                    print(error.code) // this will print -1009,somehow it means , there is no internet connection
                    self.errorCode = error.code

    }
      //check for other error.code    

}else{
  //there is no problem
}

the error.code will tell you what is the problem

like image 22
Hamid Shahsavari Avatar answered Oct 11 '22 05:10

Hamid Shahsavari