在创建AVAssetDownloadURLSession之前,需要在AppDelegate中设置NSURLSessionConfiguration并创建URLSession。以下是示例代码:
在AppDelegate中:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let backgroundConfiguration = URLSessionConfiguration.background(withIdentifier: "yourIdentifer") backgroundConfiguration.sessionSendsLaunchEvents = true
let downloadSession = URLSession(configuration: backgroundConfiguration, delegate: self, delegateQueue: OperationQueue.main)
downloadSession.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
for downloadTask in downloadTasks {
downloadTask.cancel()
}
}
downloadSession.finishTasksAndInvalidate()
return true
}
在ViewController中:
let urlAsset = AVURLAsset(url: videoURL) let downloadTask = downloadSession.makeAssetDownloadTask(asset: urlAsset, assetTitle: "title", assetArtworkData: nil, options: nil) downloadTask?.resume()
注意:此代码在Swift 5.0上测试通过。如果使用的是其他版本的Swift,请确认代码是否适用。