Can this image download technique use timeouts: Why doesn't image load on main thread??
Or must I use NSURLSession instead if I want to use timeouts?
Can this image download technique use timeouts: Why doesn't image load on main thread??
Or must I use NSURLSession instead if I want to use timeouts?
You are looking for the timeoutintervalForResource
property. If you use URLSession.shared
, the default timeout is 7 days. If you want to use a different timeout, you need to create your own session:
let config = URLSessionConfiguration.default
config.timeoutIntervalForResource = 60 // timeout, in seconds
// A 20 MB image from NASA
let url = URL(string: "https://www.nasa.gov/sites/default/files/thumbnails/image/hs-2015-02-a-hires_jpg.jpg")!
let session = URLSession(configuration: config)
session.dataTask(with: url) { data, response, error in
if let error = error {
print(error)
}
// do something
}.resume()
Lower the timeout enough and you will see a timeout error. Note that URLSessionConfiguration
has 2 timeouts: timeoutIntervalForResource
and timeoutIntervalForRequest
:
...Resource
is the time to wait for whole network operation to finish (default is 7 days)...Request
is the time to wait for next chunk of data to arrive (default is 60 seconds)If your goal is to download something in x minutes, using ...Resource
. If your goal is "network must response within x seconds or it's down", use ...Request
.
No, you don't have to use NSURLSession. The timeout properties are in URLSesssionConfiguration and you just need to create an instance of URLSession using your desired configuration.
So, rather than using URLSession.shared
directly you would need to make your own instance of URLSession and start the dataTask
from that instance.
You are probably interested in timeoutIntervalForResource, which I think defaults to 7 days.
Here is a relevant Swift fragment from the answer to this question:
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 30.0
sessionConfig.timeoutIntervalForResource = 60.0
let session = URLSession(configuration: sessionConfig)