NSURLSession error handling

19,790

Solution 1

Look at the code and domain of the resulting NSError object. You can diagnose why it failed looking at those.

For example, a domain of NSURLErrorDomain and a code of -1009 means you're not connected to the internet. So in Swift 3:

if let error = error as? NSError, error.domain == NSURLErrorDomain, error.code == NSURLErrorNotConnectedToInternet {
    print("not connected")
}

You can see a list of these codes in the Global Variables - Foundation Constants Reference. Just explore under the "NSURL Domain".

Also, search for NSURLErrorNotConnectedToInternet by pressing command+shift+o and then, you'll be taken to the relevant header (NSURLError.h). Personally for this sort of stuff, I tend to trust the headers a little more than the documentation. If you do this search when working with Objective-C, you'll even see cross reference to CFURLError codes (which you can either command-click on or command+shift+o and search for kCFURLErrorNotConnectedToInternet), and if you explore those, you'll actually see the numeric values associated with these constants.

Solution 2

Swift 4

if let error = error as NSError?, error.domain == NSURLErrorDomain && error.code == NSURLErrorNotConnectedToInternet {
      //not connected
}
Share:
19,790
MobileMon
Author by

MobileMon

Updated on July 21, 2022

Comments

  • MobileMon
    MobileMon almost 2 years

    Using Swift and NSURLSession. The NSError localizedDescription I get is very generic when I don't have internet connection (manually turned off wifi/cell network). It says "The operation couldn’t be completed."

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    

    I'm looking for a more specific message to send to the user. I enabled a breakpoint and inspected all objects but can't find anything good.

    Prior to swift I was using AFNetworking with objective C:

    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    

    The error messages I would get here were very descriptive, something like "the internet connection appears to be offline"