session.dataTask 在 swift 中是异步的吗? [英] is session.dataTask asynchronous in swift?

查看:92
本文介绍了session.dataTask 在 swift 中是异步的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码向我的服务器发出请求:

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 {

}

还是 dataTask 本身是异步请求的,以免阻塞主线程并将其分派到另一个线程将是多余的?

Or is dataTask itself requested asynchronously so as not to block the main thread and dispatching this to another thread will be redundant?

推荐答案

是系统给定的 URLSession dataTask 本质上是 async.每当有一个带有完成处理程序的系统 API 调用时,API 本质上总是 async.结论,上述实现是正确的.您不需要将任务放入全局队列中.

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.

这篇关于session.dataTask 在 swift 中是异步的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆