0

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?

4thSpace
  • 43,672
  • 97
  • 296
  • 475

2 Answers2

4

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.

Code Different
  • 90,614
  • 16
  • 144
  • 163
0

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)
ozzieozumo
  • 426
  • 2
  • 8
  • Do you have a link to an example using it as an instance rather than shared? – 4thSpace Dec 26 '17 at 20:22
  • There are several examples on SO and other sources showing Swift3/4 code for URL session with a non-standard configuration. I copied one such example for you. You should be able to work it out from here. – ozzieozumo Dec 26 '17 at 23:15