当应用程序为后台时调用URLSession.shared.dataTask
问题描述:
我尝试在应用程序处于后台或挂起状态时将数据发回服务器。我使用yes和no操作实施了可操作的推送通知。我必须更新后端,并点击yes或no。 我的下面的代码工作正常,如果应用程序在前台运行,但它在后台或挂起状态失败。任何人都可以知道如何处理这个问题。当应用程序为后台时调用URLSession.shared.dataTask
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)
,并使用该会话,使您的数据任务
请注意,使用背景会话配置时,你不能让一个数据任务与完成块。你应该使用委托。
希望有所帮助。