Vahid
Vahid

Reputation: 1949

Swift background data task

I'm trying to make a background post request in Swift. I know that I should configure a background URLSession and use a delegate instead of a completion handler.

Here's the delegate I'm using:

class Delegate:NSObject, URLSessionDelegate, URLSessionTaskDelegate,
URLSessionDataDelegate{
    var completionHandler:((String) -> Void)?
    func urlSession(_ session: URLSession,
                    dataTask: URLSessionDataTask,
                    didReceive response: URLResponse,
                    completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        completionHandler(URLSession.ResponseDisposition.allow)
    }
    func urlSession(_ session: URLSession,
                    dataTask: URLSessionDataTask,
                    didReceive data: Data) {
        let responseString = String(data: data, encoding: .utf8)!
        if let handler = self.completionHandler {
            handler(responseString)
            session.finishTasksAndInvalidate()
        }
    }
}

And this is how I'm launching the data task:

let url = URL(string: endpoint)
var request = URLRequest(url: url!)
request.setValue("text/xml", forHTTPHeaderField: "Content-Type")
request.httpBody = body.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
request.httpMethod = "POST"    
let delegate = Delegate()
delegate.completionHandler = {
    data in
    // use the data
}
let config = URLSessionConfiguration.background(withIdentifier: "id-background")
let session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil)
let task = session.dataTask(with: request)
task.resume()

This still works only in foreground.

What am I missing here?

Upvotes: 2

Views: 4052

Answers (1)

Martin Prusa
Martin Prusa

Reputation: 211

you will need to implement AppDelegate method

and this into your delegate

Also, you should implement background modes. A relative answer to your question could be found here. URLSession.datatask with request block not called in background

Upvotes: 2

Related Questions