使用API 的后台/主线程中的错误

问题描述 投票:0回答:1

我尝试调用我的API,但出现错误

Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.

我了解我需要致电DispatchQueue,但我不知道需要在哪里使用它。

我的代码:

let currentUser = Auth.auth().currentUser
currentUser?.getIDTokenForcingRefresh(true, completion: { (idToken, error) in
    if let err = error {
        self.unknownError(error: err)
    } else {
        var request = URLRequest(url: URL(string: "https://phss.ru/api/booking/cancel")!)
        request.httpMethod = "POST"
        let cancelBooking: [String: Any] = ["booking_id": self.documentIDs]
        let jsonData = try! JSONSerialization.data(withJSONObject: cancelBooking, options: [])
        request.httpBody = jsonData
        request.addValue("Bearer \(idToken!)", forHTTPHeaderField: "Authorization")
        let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
            if let err = error {
                self.unknownError(error: err)
            } else {
                let alertController = UIAlertController(title: NSLocalizedString("Cancel successful", comment: "Cancel successful"), message: "", preferredStyle: .alert) 
                alertController.addAction(UIAlertAction(title: NSLocalizableOk, style: .cancel, handler: nil))
                self.present(alertController, animated: true, completion: nil)
            }
        })
    task.resume()
    }
})
ios swift xcode api nsurlsession
1个回答
0
投票

您需要将UIAlertController内容包装在主队列中,因为URLSession.shared.dataTask(的回调在后台线程中运行

DispatchQueue.main.async {
   let alertController = UIAlertController(title: NSLocalizedString("Cancel successful", comment: "Cancel successful"), message: "", preferredStyle: .alert) 
   alertController.addAction(UIAlertAction(title: NSLocalizableOk, style: .cancel, handler: nil))
   self.present(alertController, animated: true, completion: nil)
}
© www.soinside.com 2019 - 2024. All rights reserved.