ios - 在 applicationWillTerminate 中发送请求

标签 ios swift url request xcode8

在我的应用程序中,当用户终止应用程序时,我需要向服务器发送一些指令。在 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/

相关文章:

ios - SCNView 由于某种原因为零

ios - 用户登录后更改菜单项

c# - 如何在 ASP.NET/C# 中检查 URL 的顶级域?

ios - objective c 将特殊 URL 转换为 NSURL

ios - UIAlertViewController : Separate tint colors for cancel and other action buttons

ios - 使用 Web 服务获取 CoreData 后台?

ios - 显示所有项目源文件?

swift - 带有 self.variable = variable 的初始化器

swift - 可以访问带问号而不带感叹号的可选变量吗?

java - 以 "&"字符为值解析 Url 中的参数的好方法是什么?