![](/img/trans.png)
[英]URLSession.shared.dataTask vs dataTaskPublisher, when to use which?
[英]Invoke URLSession.shared.dataTask when the app is background
當應用處於后台或掛起狀態時,我嘗試將數據發布回服務器。 我已經通過“是”和“否”操作實施了可行的推送通知。 我必須使用“是”或“否”來更新后端。 如果應用在前台運行,但在后台或掛起狀態下失敗,則我的以下代碼可以正常運行。 誰能知道該如何處理。
func updateEmployeeStatus(){
let json = ["id": "23", "empId": "3242", "status": "Success"] as Dictionary<String, String>
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = URL(string: "https://10.91.60.14/api/employee/status")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print("The response is",responseJSON)
}
}
task.resume()
}
要在應用程序處於后台狀態時啟動數據任務,您不能使用共享的“ URLSession”。 您必須使用后台配置實例化“ URLSession”
let bundleID = Bundle.main.bundleIdentifier
let configuration = URLSessionConfiguration.background(withIdentifier: "\(bundleID).background")
configuration.sessionSendsLaunchEvents = true
configuration.isDiscretionary = false
configuration.allowsCellularAccess = true
let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
並使用該會話進行數據任務
請注意,使用后台會話配置時,您不能使用完成塊來執行數據任務。 您應該改為使用委托。
希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.