我正在快速开发一个用作授权插件的捆绑项目,在捆绑项目中我正在使用 API 请求调用URLSession.shared.dataTask
,在我收到的回调中,我正在尝试更新 UI,因为更新 UI 必须是使用我正在使用的主线程完成DispatchQueue.main.async
并且里面的代码DispatchQueue.main.async
永远不会被执行!这在普通的 MacOS Cocoa 应用程序中工作得很好,但问题仍然存在于 MacOS 的 Bundle 项目中。
代码:
class MainForm: NSWindowController{
public var bodyParams: [String: Any]?
override func windowDidLoad() {
super.windowDidLoad()
testfetch{ (Response) in
os_log("In completion handler response: %@", Response)
//code to update some UI follows
}
}
func testfetch(completion: @escaping (Response) -> ()){
os_log("Is this mainthread in testFetch %@", Thread.isMainThread ? "Yes" : "No")
os_log("Current thread testFetch %@", Thread.current)
let url = URL(string: "https://example.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
bodyParams = ["username": "******", "password": "*****"]
if let bodyParams = bodyParams {
guard let body = try? JSONSerialization.data(withJSONObject: bodyParams, options: []) else {
return
}
request.httpBody = body
let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
guard let data = data else {
os_log("Data not recieved!!")
return
}
os_log("Is this mainthread in dataTask %@", Thread.isMainThread ? "Yes" : "No")
os_log("Current thread in dataTask %@", Thread.current)
os_log("Data recieved in testFetch: %@", String(data: data, encoding: .utf8)!)
do{
let receivedData = try JSONDecoder().decode(Response.self, from: data)
DispatchQueue.main.async{
os_log("Is this mainthread in main.async %@", Thread.isMainThread ? "Yes" : "No")
os_log("Current thread in main.async %@", Thread.current)
completion(receivedData)
}
}
catch let Err{
os_log("Error is: %@", Err as! String)
}
}
task.resume()
}
}
struct Response: Codable {
let name, age, status: String
}
}
日志:
Is this mainthread in testFetch? Yes
Current thread testFetch <NSThread: 0x7f9176001c30>{number = 1, name = main}
Is this mainthread in dataTask No
Current thread in dataTask <NSThread: 0x7f9173dc2080>{number = 4, name = (null)}
Data recieved in testFetch: {"name":"JohnDoe", "age": "**", "status": "single"}
所以登录DispatchQueue.main.async
和完成处理程序永远不会被打印出来。我对快速和异步编程很陌生,任何帮助将不胜感激!