【问题标题】:Error in background/main thread using API使用 API 在后台/主线程中出错
【发布时间】:2020-03-13 02:58:20
【问题描述】:

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

【问题讨论】:

标签: ios swift xcode api nsurlsession


【解决方案1】:

您需要在主线程上显示您的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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多