【问题标题】:Invoke URLSession.shared.dataTask when the app is background当应用程序处于后台时调用 URLSession.shared.dataTask
【发布时间】:2017-11-06 22:15:54
【问题描述】:

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

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()
}

【问题讨论】:

    标签: ios swift3 background nsurlsessiondatatask


    【解决方案1】:

    要在您的应用程序处于后台状态时启动数据任务,您不能使用共享的“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)
    

    并使用该会话来完成您的数据任务

    请注意,当使用后台会话配置时,您不能使用完成块创建数据任务。您应该改用委托。

    希望对您有所帮助。

    【讨论】:

    • "请注意,当使用后台会话配置时,您不能使用完成块创建数据任务。您应该改用委托。" ——你能详细说明吗?我很难理解如何在没有完成处理程序的情况下将我的 URLSession.shared.dataTask 转换为一个。
    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    相关资源
    最近更新 更多