is session.dataTask asynchronous in swift?
Asked Answered
J

1

5

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?

Junction answered 26/10, 2017 at 12:19 Comment(3)
What session are you using? It's is async yesLithoid
Something else is definitely blocking itKartis
I just edited to include the session with is default configurationJunction
C
6

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.

Charla answered 26/10, 2017 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.