gpt4 book ai didi

ios - 使用 API 时后台/主线程出错

转载 作者:行者123 更新时间:2023-11-29 05:18:45 26 4
gpt4 key购买 nike

我尝试调用我的 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()
}
})

最佳答案

您需要在主线程上显示您的 UIAlertController,因为 URLSession.shared.dataTask(with:completionHandler:) 的完成回调在后台线程上运行。

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

关于ios - 使用 API 时后台/主线程出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58902724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com