NSURLSession timeout

2019-04-02 15:21发布

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()

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-02 15:55

You cannot change the timeout on the sharedSession or a sessions configuration 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

查看更多
登录 后发表回答