![](/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.