0

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()
}
Warrior
  • 39,156
  • 44
  • 139
  • 214

1 Answers1

0

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.

Mourad Brahim
  • 531
  • 2
  • 15
  • "Please note that when using a background session configuration you cant make a data task with a completion block. You should use delegate instead." -- Can you elaborate? I'm having a hard time understanding how to convert my `URLSession.shared.dataTask` to one without a completion handler. – David Vincent Gagne Oct 19 '18 at 15:53