Looking at the documentation for URLSession.dataTask
it's clear this function is called asynchronously but there's no mention of whether the completionHandler returns to the main thread, the thread which called it or remains on the thread the dataTaskOperation was performed on.
Is there a general convention to expect here?
let task = URLSession.shared().dataTask(with: request) {
//What Thread are we on here?
}
From the documentation of the completionHandler
parameter of URLSession dataTask
:
This handler is executed on the delegate queue.
So the next question is, what is the delegate queue? That all depends on how the URLSession
was setup. You are using the shared
session which sets a nil
delegate queue. The documentation for the queue
parameter of the init
method states:
If nil, the session creates a serial operation queue for performing all delegate method calls and completion handler calls.
So the code you posted results in the completion handler being called on a background serial queue.