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.
URLSession
In the documentation it says...
This handler is executed on the delegate queue.
And looking at the delegate queue...
All delegate method calls and completion handlers related to the session are performed on this queue. The session object keeps a strong reference to this queue until your app exits or the session object is deallocated. If you do not invalidate the session, your app leaks memory until it exits.
Note
This queue must be set at object creation time and may not be changed.
And looking at the init method...
It doesn't actually say anything about what type of queue is used...
Hmm...
As pointed out by @rmaddy a serial queue is created by the session so that would run on a background thread.
Conventions
As for conventions... there isn't really one.
If you write your own there are things to consider... is the completion likely going to update the UI? Will the completion do lots of data processing etc... and you can decide from there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With