在我的应用程序中,当用户终止应用程序时,我需要向服务器发送一些指令。在 applicationWillTerminate func 中,我尝试发送它,但它从未到达服务器。我尝试使用 Alamofire 和 native URLSession 但它不起作用。有人知道我该如何发送吗? 我用这个代码
let request = "\(requestPrefix)setDriverOrderStatus"
if let url = URL(string:request) {
var parameters : [String : String] = [:]
parameters["access_token"] = UserSession.accessToken
parameters["driver_id"] = UserSession.userID
parameters["status"] = status
var req = URLRequest(url: url)
req.httpMethod = HTTPMethod.put.rawValue
do {
req.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
_ = URLSession.shared.dataTask(with: req, completionHandler: { data, response, error in
guard error == nil else {
print(error ?? "error")
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: [])
print(json)
}).resume
}
最佳答案
对我有用的一个解决方案是在 applicationWillTerminate
函数的末尾添加 sleep ,如下所示:
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
// HERE YOU will make you HTTP request asynchronously
self.postLogoutHistory()
// 3 is the number of seconds in which you estimate your request
// will be finished before system terminate the app process
sleep(3)
print("applicationWillTerminate")
// self.saveContext()
}
关于ios - 在 applicationWillTerminate 中发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41393966/