Ios 后台/主线程使用API时出错
我尝试调用我的API,但出现错误: 从主线程访问布局引擎后,不得从后台线程执行对布局引擎的修改 我知道我需要调用Ios 后台/主线程使用API时出错,ios,swift,xcode,api,nsurlsession,Ios,Swift,Xcode,Api,Nsurlsession,我尝试调用我的API,但出现错误: 从主线程访问布局引擎后,不得从后台线程执行对布局引擎的修改 我知道我需要调用DispatchQueue,但我不知道我需要在哪里使用它 我的代码: let currentUser = Auth.auth().currentUser currentUser?.getIDTokenForcingRefresh(true, completion: { (idToken, error) in if let err = error { self.u
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)
}
这回答了你的问题吗?