michaelteddy

Q: URLSession Background

I am building an app on Xcode 8 using Swift 3. My app receives a push notification from my server and responds with the current device latitude and longitude using Http Post method. But when my app is in the background, it receives the push notification but the Http Post is not called until I bring the app back to the foreground.

 

So I tried adding the following code

let config = URLSessionConfiguration.background(withIdentifier: "sample")

session1 = URLSession(configuration: config, delegate: self, delegateQueue: nil)

// Posting Request

        let task = session1.dataTask(with: request as URLRequest, completionHandler: {

            data, response, error in

            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

            print("Response String = \(responseString)")

        })

        task.resume();

and I get following error message

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Completion handler blocks are not supported in background sessions. Use a delegate instead.'


Please help.

iPhone 5s, iOS 10.0.2

Posted on Sep 26, 2016 9:29 PM