I am working on a bundle project in swift for MacOS which is used as an authorization plugin which runs at login (https://developer.apple.com/documentation/security/authorization_plug-ins/using_authorization_plug-ins) 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!