13

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.

SphericalCow
  • 345
  • 1
  • 2
  • 13
  • I'm not sure if it applies to `NSURLSession`, but `NSURLConnection` will fail and the delegate method will be called with an error code of `NSURLErrorTimeOut`, as described in this answer: http://stackoverflow.com/a/12819297/433373 (EDIT: that answer id about `-sendSynchronousRequest:returningResponse:error:`, but `-connection:didFailWithError:` also returns an `NSError` object. You can check that) – Nicolas Miari Jul 13 '15 at 05:38

2 Answers2

23

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()
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
  • Does not look very robust (or future proof). You are hard-coding the error description; it might change in a future OS update (not to manetion that the user might have their device set to another language than english). – Nicolas Miari Jul 13 '15 at 05:33
6

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

}
AamirR
  • 11,672
  • 4
  • 59
  • 73