我尝试在应用程序处于后台或挂起状态时将数据发回服务器。我已经通过是和否操作实现了可操作的推送通知。我必须通过点击是或否来更新后端。 如果应用程序在前台运行但在后台或挂起状态下失败,我下面的代码可以正常工作。任何人都知道如何处理这个。
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)
并使用该 session 来完成您的数据任务
请注意,当使用后台 session 配置时,您不能使用完成 block 创建数据任务。您应该改用委托(delegate)。
希望对您有所帮助。
关于ios - 当应用程序处于后台时调用 URLSession.shared.dataTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44380813/