Swift 当我的应用程序进入后台时,后台下载任务暂停

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

我正在尝试创建一个下载任务,即使应用程序在后台也能继续下载视频。

所以我按照苹果文档创建了一个 url 会话作为后台。 当我通过点击按钮开始下载过程时,我将打印下载进度。 但是,当应用程序进入后台时,应用程序停止打印进度。

我想知道我错过了什么,或者误解了什么。

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)")
        }
 }

您需要配置后台任务以使其正常工作。

有关配置后台任务的更多详细信息,请查看此苹果官方开发者文档

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