Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 后台/主线程使用API时出错_Ios_Swift_Xcode_Api_Nsurlsession - Fatal编程技术网

Ios 后台/主线程使用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

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

从主线程访问布局引擎后,不得从后台线程执行对布局引擎的修改

我知道我需要调用
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)
}

这回答了你的问题吗?