I have a function where I make a request to get a JSON
.
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
let session = NSURLSession.sharedSession()
session.configuration.timeoutIntervalForRequest = 5
session.configuration.timeoutIntervalForResource = 5
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data!)
onCompletion(json, error)
})
task.resume()
This works, but I´m having issues with the timeout. If the request takes more than 5 seconds I want to cancel the operation. Any ideas how to do this?
The call can take more than 5 seconds but it stills fires and the timeout does not do anything. Do I have to do anything if the timeout is fired?
Update
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
let urlconfig = NSURLSessionConfiguration.defaultSessionConfiguration()
urlconfig.timeoutIntervalForRequest = 5
urlconfig.timeoutIntervalForResource = 5
let session = NSURLSession(configuration: urlconfig, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data!)
onCompletion(json, error)
})
task.resume()
You cannot change the timeout on the
sharedSession
or a sessionsconfiguration
property. You have to set the timeout when the session is created. See this for an example of how to create a session and its timeout: https://stackoverflow.com/a/30427187/78496