Ale*_*nik 0 url request ios swift xcode8
在我的应用程序中,当用户终止应用程序时,我需要向服务器发送一些指令。在applicationWillTerminate函数中,我尝试发送它,但是它从未发送到服务器。我尝试使用Alamofire和本机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
}
Run Code Online (Sandbox Code Playgroud)
对我applicationWillTerminate
有用的一种解决方案是在函数的末尾添加睡眠,如下所示:
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()
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1866 次 |
最近记录: |