How to resume URLSessionDownloadTask after app termination?

82 Views Asked by At

I'm using URLSessionDownloadTask to download a large ZIP file in my app. However, users may close the app while the download is in progress, especially when dealing with a single large file. In my research, I've found solutions for pausing or stopping downloads with provided buttons or functions, but I want the ability to resume downloading from the previous progress when users relaunch the app. Is this possible with URLSessionDownloadTask, or should I consider using a different library? (Note: I'm not referring to resuming downloads in the background after the app has been killed.)

    self.fileDownloadUrl = "www.example.com"
    
    var identifier: String = "com.example.app"
    
    if let downloadUrl = self.fileDownloadUrl {
        let config = URLSessionConfiguration.background(withIdentifier: identifier)
        self.session = URLSession.init(configuration: config, delegate: self, delegateQueue: nil)
        let fileUrl = URL(string: downloadUrl)!
        let request = URLRequest(url: fileUrl)
        self.task = self.session!.downloadTask(with: request)
        return
    } else {
        // Error
        return self.unownedErrorPopUp.showAnimation()
    }
1

There are 1 best solutions below

2
Duncan C On

See the docs for URLSessionConfiguration.background(withIdentifier:)

If an iOS app is terminated by the system and relaunched, the app can use the same identifier to create a new configuration object and session and to retrieve the status of transfers that were in progress at the time of termination. This behavior applies only for normal termination of the app by the system. If the user terminates the app from the multitasking screen, the system cancels all of the session’s background transfers. In addition, the system does not automatically relaunch apps that were force quit by the user. The user must explicitly relaunch the app before transfers can begin again.

So if the user terminates the app, your downloads will be cancelled. I'm not sure what you mean by "...a large volume can cause users to accidentally shut down the app midway." How would the user shut down the app? If they shut it down from the multitasking screen (swiping up on the app to kill it) then your background download(s) will be terminated.