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.
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()
-
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 5:33
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
}
}
}
NSURLSession
, butNSURLConnection
will fail and the delegate method will be called with an error code ofNSURLErrorTimeOut
, as described in this answer: stackoverflow.com/a/12819297/433373 (EDIT: that answer id about-sendSynchronousRequest:returningResponse:error:
, but-connection:didFailWithError:
also returns anNSError
object. You can check that) – Nicolas Miari Jul 13 '15 at 5:38