I want to make an additional HTTP request after background download/upload in order to confirm that the application finished downloading/uploading. Let me show you a simple example.
First we need to create download/upload task.
let configuration = URLSessionConfiguration.background(withIdentifier: UUID().uuidString)
configuration.sessionSendsLaunchEvents = true
configuration.isDiscretionary = true
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
session.downloadTask(with: largeFileURL).resume()
Then we need to fire some additional request after download/upload finishes. In order to prevent application from being suspended I'm using background task.
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: { [weak self] in
finishBackgroundTask()
})
let task = URLSession.shared.dataTask(with: someURL) { data, response, error in
// Process response.
finishBackgroundTask()
}
task.resume()
}
private func finishBackgroundTask() {
UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
backgroundTaskIdentifier = .invalid
}
The last thing is to implement application delegate method:
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
}
Question
Is it a proper way to make some work after background transfer?