如何在后台下载后将属性传递给 swift 3 urlsession didFinishDownloadingTo 委托?

how to pass properties to swift 3 urlsession didFinishDownloadingTo delegate after background download?

我可以使用 ios 10 和 swift 3 的应用程序代码在后台成功下载 zip 文件。

我使用后台会话数据任务:

let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: (prefix + postfix))
        let backgroundSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)

        var request = URLRequest(url: dlUrl )
        request.httpMethod = "GET"
        request.cachePolicy = NSMutableURLRequest.CachePolicy.reloadIgnoringCacheData

        let task = backgroundSession.downloadTask(with: request)

        task.resume()

但我想知道在下载完成后将一些特定元数据传递给委托方法的最佳做法是什么:

    func urlSession(_ session: URLSession,
    downloadTask: URLSessionDownloadTask,
    didFinishDownloadingTo location: URL){

我需要在这个委托中有一些关于下载的信息,这取决于例如根据用户之前做出的选择。我无法从服务器或 url.

获取此数据

所以我想要一个变量或字典 downloadType 告诉我如何处理完成的下载,在委托中有这样的东西

if downloadType == "normal" ... do this
else ... do that

我不确定在应用程序暂停时是否可以安全地使用实现 URLSessionDownloadDelegate 协议的 class 的属性? class 实例本身会在应用程序暂停时下载完成时恢复,还是 ios 创建 class 的新实例?

所以这会一直有效吗:

class ServerCom: NSObject, URLSessionDownloadDelegate {
   var updateTypeStr = ""
  [...]
  func somePublic(setUpdateType: String) {
     self.updateTypeStr = setUpdateType

  [...]
    func urlSession(_ session: URLSession,
    downloadTask: URLSessionDownloadTask,
    didFinishDownloadingTo location: URL){
   [...] 

       if( self.updateTypeStr == "normal" ) { // do this
       else { // do that

对于该用例是否有更好的方法?

提前致谢!

Will the class instance itself be restored when the download finishes while the app is suspended or will ios create a new instance of the class?

您有责任自行保存和恢复。

您的应用程序可能会在守护进程完成您的后台请求期间完全终止(例如已挂起,可能由于内存压力而被丢弃),因此您必须能够保存任何相关信息到持久存储,并能够在应用程序重新启动时从存储中加载它。

在使用后台会话测试应用程序时,我发现让代码调用 exit(0) 来终止应用程序很有用。您永远不会在生产应用程序中这样做,但在测试您的应用程序在后台请求完成后重新启动应用程序时重新创建必要对象的能力时,它很有用。关键是在进行此测试时不应尝试使用 "double tap home button and swipe up" 来终止应用程序,因为根据设计,这也会取消后台请求。您想测试您的应用程序在正常应用程序生命周期内终止并在后台请求完成后由网络守护程序重新启动的场景。