URLSession Waiting For Connectivity

If you use URLSession to start a task with iOS 10 and the network is not available the connection fails at once with an error. There was a small change in iOS 11 that means you can now tell your URLSession to wait until network connectivity is available before trying the connection.

Configuring The Session

To configure a session to wait for connectivity set the waitsForConnectivity boolean to true when creating the session configuration. For example, starting with a default session configuration:

let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = 300
if #available(iOS 11, *) {
  configuration.waitsForConnectivity = true
}
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

Notes:

Also remember that URLSession keeps a strong reference to its delegate. If the session owner is also the delegate you can end up with a retain cycle unless you call invalidateAndCancel on the session at some point to release the delegate and break the cycle.

session.invalidateAndCancel() // Don't use session after this

Waiting For Connectivity

Using iOS 10 or earlier if you start a data task and there is no connectivity it fails at once. You get back an error either via the completion handler or the delegate method urlSession(_:task:didCompleteWithError:) depending on which you are using.

In iOS 11 if you set waitsForConnectivity to true the session waits (it will eventually timeout) and only starts the task if the network connection becomes available. You also get a callback to the URLSessionTaskDelegate method urlSession(_:taskIsWaitingForConnectivity:) so you can take some action:

func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
    // waiting for connectivity, update UI, etc.
}

Notes:

Read More

See this WWDC talk for the changes in URLSession in iOS 11:

I skipped a few details on how to use URLsession so if you need a recap see this earlier WWDC talk:

Never miss a post!

iOS Size Classes Cheat Sheet

Subscribe and get my free iOS Size Classes Cheat Sheet

Success! Now check your email to confirm your subscription and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
No time to watch WWDC videos?

Sign up to get my iOS posts direct to your inbox and I will send you a free PDF of my iOS Size Classes Cheat Sheet.

OK! Check your inbox (or spam folder) for an email to confirm your details and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
Archives Categories