4

I am using an Alamofire 4. When I do

print(response.debugDescription)

I have something like this in the console:

[Request]: https://api2.website.com
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={NSUnderlyingError=0x17444ace0 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x170490e50 [0x1ab165bb8]>{length = 16, capacity = 16, bytes = 0x100201bb341d1f890000000000000000}, _kCFStreamErrorCodeKey=57, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey=https://api2.flowwow.com/api2/client/info/?auth_token=da88d8aa49ff6f8bb4e1&hash=7f38be3f68db39a6d88687505fdb9ba5&partner_id=1004, NSErrorFailingURLKey=https://api2.website.com, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=57, NSLocalizedDescription=The Internet connection appears to be offline.}
[Timeline]: Timeline: { "Request Start Time": 510763454.078, "Initial Response Time": 510763455.293, "Request Completed Time": 510763455.293, "Serialization Completed Time": 510763455.297, "Latency": 1.215 secs, "Request Duration": 1.215 secs, "Serialization Duration": 0.005 secs, "Total Duration": 1.220 secs }

And there is a particular line which interests me:

Error Domain=NSURLErrorDomain Code=-1009

How can I get this Code so I can handle the error correctly. I tried all combinations I could make up but there is no trace of this code anywhere.

Eduard
  • 516
  • 1
  • 4
  • 17
  • I think that [this question/answers](http://stackoverflow.com/questions/29131253/swift-alamofire-how-to-get-the-http-response-status-code) should be useful, or maybe [this one](http://stackoverflow.com/questions/36331234/could-not-get-the-server-error-message-from-alamofire-3-3-0). – Ahmad F Mar 09 '17 at 15:02
  • @AhmadF Yeah, I have checked this ones out before posting — it didn't help. – Eduard Mar 09 '17 at 15:33
  • @Eduard Did you find a solution ? in Alamofire 5 error._code does not returns the expected matching number – MFAL Apr 01 '20 at 12:16

3 Answers3

13

when you make calls with Alamofire, it returns a response where you can check for any errors. This is a simple example of error handling call with Alamofire.

Alamofire.request("https://your.url.com").responseJSON { response in
    if (response.result.isSuccess){
        //do your json stuff
    } else if (response.result.isFailure) {
        //Manager your error
        switch (response.error!._code){
            case NSURLErrorTimedOut:
                //Manager your time out error
                break
            case NSURLErrorNotConnectedToInternet:
                //Manager your not connected to internet error
                break
            default:
                //manager your default case 
            }
    }
}

Enjoy :)

Updated on 1st April 2020

This code should works on Alamofire 5 version. I still didn't check, let me know if this works

AF.request(route).responseJSON { (response) in
    let result = response.result
    switch result {
    case .success(let value):
        print("Success")
        // Do something with value
    case .failure(let error):

        if let underlyingError = error.underlyingError {
            if let urlError = underlyingError as? URLError {
                switch urlError.code {
                case .timedOut:
                    print("Timed out error")
                case .notConnectedToInternet:
                    print("Not connected")
                default:
                    //Do something
                    print("Unmanaged error")
                }
            }
        }
    }
}

I hope this works :)

Alessandro
  • 2,927
  • 1
  • 10
  • 14
  • is it possible that this solution is no longer working on v5 ? A logged error with Code=-1200 is being read in response.error!._code as 13 . Therefore the switch fail. – MFAL Apr 01 '20 at 12:14
  • Yes I experience the same thing. Have you found a solution to this problem= – JMIT Apr 01 '20 at 15:58
  • @MFAL i don't know but it could be possible – Alessandro Apr 01 '20 at 16:22
  • @MFAL i tried a new implementation with Alamofire 5 but still not tried. If you can try it and let me know if this works :) – Alessandro Apr 01 '20 at 17:16
  • @Alessandro ... Yes it works... just need to compare the .rawValue in the switch. urlError.code.rawValue instead. – MFAL Apr 02 '20 at 15:46
  • @JMIT ... solution found. Thanks to Alessandro . – MFAL Apr 02 '20 at 15:49
1

Alamofire request sample

let request = Alamofire.request(urlString,
                                               method: method,
                                               parameters: parameters,
                                               encoding: encoding,
                                               headers: defaultHeaders())

/// Response Status code 
/// This status code will be the response’s HTTP status code.
request.responseJSON { response in
        if let code = response.response?.statusCode {
            NSLog("  Received response: \(code) \(HTTPURLResponse.localizedString(forStatusCode: code))")
        }
        switch response.result {
        case .success:
            /// Parse data
            parseData(rawdata: response.data, completion: completion)
        case .failure(let error):
            parseFailure(response, error, completion)
        }
    }

Hope this helps!!

Sumit
  • 874
  • 9
  • 10
0

Updated on 1st April 2022

This code should works on Alamofire 5 version.

AF.request(route).responseJSON { (response) in
    let result = response.result
    switch result {
    case .success(let value):
        print("Success")
        // Do something with value
    case .failure(let error):

        if let underlyingError = error.asAFError?.underlyingError {
            if let urlError = underlyingError as? URLError {
                switch urlError.code {
                case .timedOut:
                    print("Timed out error")
                case .notConnectedToInternet:
                    print("Not connected")
                default:
                    //Do something
                    print("Unmanaged error")
                }
            }
        }
    }
}