I am trying to upload large files from iOS to a server using URLSessionConfiguration.background
object and uploadTask
function.
Things are looking good til now, but I wonder what actually happens behind the scene when the app goes into background state. I looked up the documents but it only roughly says "the session hands the transfers over to the system".
What I've done is just to initialize a singleton UploadManager
again in application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void)
after the tasks were done while in background. The manager instance creates a new URLSession
with the same identifier inside of it.
I thought I am just apparently creating "another" URLSession instance again, but how does it know about the previous tasks and their states to call the appropriate delegate methods? Does it receive the information back from process running by the system?
class UploadManager {
static let shared = UploadManager()
private var urlSession: URLSession!
private init() {
let sessionConfig = URLSessionConfiguration.background(withIdentifier: Bundle.main.bundleIdentifier! + ".upload")
sessionConfig.networkServiceType = .video
urlSession = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
}
...
}
extension UploadManager {
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
// do post-upload process for completed jobs
}
}
class AppDelegate: ... {
...
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
NSLog(" backgroundURLSession is done \(identifier)")
// just by instantiating, the appropriate completion delegate is called
let manager = VideoUploadManager.shared
}
}