Reputation: 9743
I am making requests to my server using the following code:
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in
if error != nil {
DispatchQueue.main.async(execute: {
completion(nil, error as NSError?)
})
return
}
DispatchQueue.main.async(execute: {
code...
})
}
dataTask.resume()
From what I have read this should not block the main thread but it seems to be doing just that. Do I need to call this code after dispatching to another thread? i.e.:
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
}
Or is dataTask itself requested asynchronously so as not to block the main thread and dispatching this to another thread will be redundant?
Upvotes: 5
Views: 3686
Reputation: 126
Yes system given URLSession
dataTask
is async
in nature. Whenever there is a system API call with a completion handler, the API is always async
in nature. Concluding, the above implementation is correct. You don't need to put the task in the global queue.
Upvotes: 6