Search code examples
swiftalamofire

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).


Solution

  • 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...