Code block in DispatchQueue.main.async is never getting executed

时光毁灭记忆、已成空白 提交于 2020-04-18 12:36:23

问题


I am working on a bundle project in swift which is used as an authorization plugin and in the bundle project I am doing API request call using URLSession.shared.dataTask and in the call back I receive, I am trying to update the UI and as updating UI has to be done using main thread I am using DispatchQueue.main.async and the code inside DispatchQueue.main.async is never getting executed! This works perfectly fine in a normal MacOS Cocoa application but the problem persists with Bundle project for MacOS.

CODE:

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
    }
}


Logs:

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"}

So the logs in DispatchQueue.main.async and completion handler are never getting printed. I am quite new to swift and async programming any help would be much appreciated!

来源:https://stackoverflow.com/questions/60723997/code-block-in-dispatchqueue-main-async-is-never-getting-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!