Search code examples
iosswiftdownloadbackground

Swift background download task got suspended when I application goes into background


I am trying to create a download task that will continue to download a video even when the application is in the background.

So I followed the apple documentation to create a url session as background. When I started the download process by tapped a button, I will print the progress of the download. However, the application stops printing the progress when the application goes into background.

I wonder what did I miss, or misunderstand.

class ViewController: UIViewController {
  private lazy var urlSession: URLSession = {
      let config = URLSessionConfiguration.background(withIdentifier: "MySession")
      config.isDiscretionary = true
      config.sessionSendsLaunchEvents = true
      return URLSession(configuration: config, delegate: self, delegateQueue: 
      OperationQueue())
  }()
  var downloadUrl = "https://archive.rthk.hk/mp4/tv/2021/THKCCT2021M06000036.mp4"

  override func viewDidLoad() {
      super.viewDidLoad()
  }

  @IBAction func downloadButtonTapped(_ sender: UIButton) {
      print("DownloadButton Tapped")
      let url = URL(string: downloadUrl)

      guard let url = url else {
         print("Invalid URL")
         return
      }

      let downloadTask = urlSession.downloadTask(with: url)
    
      downloadTask.resume()
  }

}

  extension ViewController: URLSessionDownloadDelegate, URLSessionDelegate {
        func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, 
           didFinishDownloadingTo location: URL) {
           print("Downloaded, location: \(location.path)")
        }

        func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, 
           didWriteData bytesWritten: Int64, totalBytesWritten: Int64, 
           totalBytesExpectedToWrite: Int64) {
           let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
           print("Progress: \(progress)")
        }
 }

Solution

  • You need to configure the background tasks to make that work properly.

    For more details to configure background tasks please check this official apple developer documentation

    https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_in_the_background