ios - 当应用程序处于后台时调用 URLSession.shared.dataTask

标签 ios swift3 background nsurlsessiondatatask

我尝试在应用程序处于后台或挂起状态时将数据发回服务器。我已经通过是和否操作实现了可操作的推送通知。我必须通过点击是或否来更新后端。 如果应用程序在前台运行但在后台或挂起状态下失败,我下面的代码可以正常工作。任何人都知道如何处理这个。

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/

相关文章:

ios - 应用程序在后台运行3分钟

ios - 如何在post方法ios中向服务器请求数据?

ios - 丹麦语本地化在 iOS 8 中被破坏?

ios - 如果找不到 whereField

ios - 将 SwiftyJSON 中的元素添加到 Swift 中的 URL 数组

jQuery:根据鼠标位置移动的全屏 "background"图像

iphone - 如何计算ios加速度计水平面

ios - 在 Swift 中根据触摸正确移动 Sprite

ios - 如何在 Swift 3 中保存顶部有图像的相机照片

ios - 在 iOS (Swift) 中使用后台位置更新的最佳方式