简体   繁体   中英

Invoke URLSession.shared.dataTask when the app is background

I am try to post data back to server when the app is in background or suspended state. I have implemented actionable push notification with yes and No actions. I have to update the backend with the yes or no is tapped. My below code works fine if the app is running in foreground but it is failing in background or suspended state. Could any one know how to handle this.

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

To start a data task when your application is in background state, you can't use the shared "URLSession". You have to instantiate an "URLSession" using a background configuration

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)

and use that session to make your data task

Please note that when using a background session configuration you cant make a data task with a completion block. You should use delegate instead.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM