首页 > 解决方案 > 如何从 URLSession.shared.dataTask(macOS 框架)返回 DispatchQueue.main

问题描述

我正在构建一个 macOS 框架,在某些时候,我需要向某些 API 发出请求

当我收到回复时,我想更新 UI。我正在使用 URLSession.shared.dataTask 进行调用,并且我知道调用是在后台线程中进行的

出于某种原因,当我尝试返回主线程时没有任何反应

我正在使用虚拟机来运行我的框架

有什么帮助吗?谢谢

这里我如何做请求:

URLSession.shared.dataTask(with: request) { data, response, error in
  if error != nil {
    DispatchQueue.main.async {
      //Display error message on the UI
      //This never happens
      //Never go back to the main thread
      //Framework stop working
    }
  }
}.resume()

标签: swiftmacosframeworksurlsession

解决方案


你确定你的任务被调用了吗?

let dataTask = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in

....

    DispatchQueue.main.async {
        completion(nil, nil)
    }
}
dataTask.resume() // You should add this. 

推荐阅读