Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 532
SphericalCow Avatar asked Jul 13 '15 04:07

SphericalCow


2 Answers

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()
like image 86
Dharmesh Kheni Avatar answered Oct 19 '22 23:10

Dharmesh Kheni


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
        }
    }

}
like image 42
AamirR Avatar answered Oct 19 '22 23:10

AamirR