IOS Swift: how to find if NSURLSession expires

In the iOS application that I am currently creating, I am trying to show a message to the user when the session timeout. I read the documentation for NSURLSessionDelegate , but could not find any method to tell if the session was expiring. How can I do it? Any help is appreciated.

+5
source share
2 answers

You can call the method as follows:

 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() 
+8
source

I use the following Swift extension to check if the error is a timeout 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 } } } 
+1
source

All Articles