当应用程序运行在后台时,下载会在一个单独的进程中运行,因此AVAssetDownloadDelegate方法不会被自动调用。要解决这个问题,需要在调用startSession方法之前向assetDownloadTask对象添加一个后台URL会话配置,并在AppDelegate中设置会话委托。示例代码如下:
//获取后台下载的会话ID let backgroundConfiguration = URLSessionConfiguration.background(withIdentifier: "com.myapp.backgroundDownload")
//创建AVAssetDownloadURLSession对象 let assetDownloadURLSession = AVAssetDownloadURLSession(configuration: backgroundConfiguration, assetDownloadDelegate: self, delegateQueue: OperationQueue.main)
//创建assetDownloadTask对象 let assetDownloadTask = assetDownloadURLSession.makeAssetDownloadTask(asset: asset, assetTitle: "Asset Title", assetArtworkData: nil, options: options)
//在AppDelegate中设置会话委托 func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) { if identifier == "com.myapp.backgroundDownload" { assetDownloadSessionCompletionHandler = completionHandler } }
//在下载完成时调用completionHandler func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { if let completionHandler = assetDownloadSessionCompletionHandler { assetDownloadSessionCompletionHandler = nil completionHandler() } }
这样,在后台下载完成后,会话委托将自动调用,并调用应用程序委托中的相应方法。