Timeout when offline iOS (using waitsForConnectivity)

515 Views Asked by At

Whilst implementing several HTTP calls, I noticed some strange behaviour on the URLSession. As far as I know, URLSession data tasks used to immediately throw an error when the network connection was unavailable (error -1009 The Internet connection appears to be offline).

I'm now performing network requests too, and while executing a request in flight mode, the request runs for as long as the timeout, before failing. I tried creating a custom configuration that should prevent this, but this does not work. How can I re-enable or configure the behaviour where a request will immediately crash when there is no connection?

let url = URL(string: "https://www.google.com/")!
let config = URLSessionConfiguration.default
config.waitsForConnectivity = false
config.timeoutIntervalForRequest = 2
config.timeoutIntervalForResource = 0

URLSession(configuration: config).dataTask(with: url) { d, r, e in
    print(d?.count, (r as? HTTPURLResponse)?.statusCode, e?.localizedDescription)
}.resume()

The configuration documentation appears to be inconsistent or incorrect.

2

There are 2 best solutions below

1
Fattie On

One factoid I've found.

Even in the latest Xcode/iOS (2024), the feature seems to not work at all in simulator.

In simulator the func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) will work, but nothing else works,

i.e. it never tries again, when bandwidth is back, regardless of any settings.

0
lorem ipsum On

the async/await data(from:url works as expected error is thrown right away.

do{
    let url = URL(string: "https://www.google.com/")!
    let config = URLSessionConfiguration.default
    config.waitsForConnectivity = false
    config.timeoutIntervalForRequest = 2
    config.timeoutIntervalForResource = 0
    
    let session = URLSession(configuration: config)
    print("call")
    let (data, response) = try await session.data(from: url)
    
    print("Done")
} catch {
    print(error)
}

I can duplicate the issue with dataTask(with: url) so I think it is worth a bug report.