SphericalCow
SphericalCow

Reputation: 365

iOS Swift : How to find if an NSURLSession has timed out

In the iOS app I am currently building, I am trying to show a message to the user when the session has timed out. I read the documentation for NSURLSessionDelegate but couldn't find out any method for letting me know if the session has timed out. How do I go about doing this? Any help is appreciated.

Upvotes: 13

Views: 14210

Answers (2)

AamirR
AamirR

Reputation: 12218

I am using following Swift extension to check whether error is time-out or other network error, using Swift 4

extension Error {

    var isConnectivityError: Bool {
        // let code = self._code || Can safely bridged to NSError, avoid using _ members
        let code = (self as NSError).code

        if (code == NSURLErrorTimedOut) {
            return true // time-out
        }

        if (self._domain != NSURLErrorDomain) {
            return false // Cannot be a NSURLConnection error
        }

        switch (code) {
        case NSURLErrorNotConnectedToInternet, NSURLErrorNetworkConnectionLost, NSURLErrorCannotConnectToHost:
            return true
        default:
            return false
        }
    }

}

Upvotes: 6

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71852

You can call method this way:

let request = NSURLRequest(URL: NSURL(string: "https://evgenii.com/")!)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in

        if error != nil {

            if error?.code ==  NSURLErrorTimedOut {
                println("Time Out")
                //Call your method here.
            }
        } else {

            println("NO ERROR")
        }

    }
    task.resume()

Upvotes: 23

Related Questions