URLSession downloadTask 在后台运行时的行为?
Posted
技术标签:
【中文标题】URLSession downloadTask 在后台运行时的行为?【英文标题】:URLSession downloadTask behavior when running in the background? 【发布时间】:2017-10-25 17:59:39 【问题描述】:我有一个应用程序需要下载一个可能相当大的文件(可能大到 20 MB)。我一直在阅读 URLSession downloadTasks 以及当应用程序进入后台或被 ios 终止时它们是如何工作的。我希望继续下载,从我读过的内容来看,这是可能的。我找到了一篇博文here,详细讨论了这个话题。
根据我的阅读,我首先创建了一个下载管理器类,如下所示:
class DownloadManager : NSObject, URLSessionDownloadDelegate, URLSessionTaskDelegate
static var shared = DownloadManager()
var backgroundSessionCompletionHandler: (() -> Void)?
var session : URLSession
get
let config = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).background")
return URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
private override init()
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession)
DispatchQueue.main.async
if let completionHandler = self.backgroundSessionCompletionHandler
self.backgroundSessionCompletionHandler = nil
completionHandler()
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
if let sessionId = session.configuration.identifier
log.info("Download task finished for session ID: \(sessionId), task ID: \(downloadTask.taskIdentifier); file was downloaded to \(location)")
do
// just for testing purposes
try FileManager.default.removeItem(at: location)
print("Deleted downloaded file from \(location)")
catch
print(error)
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
if totalBytesExpectedToWrite > 0
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
let progressPercentage = progress * 100
print("Download with task identifier: \(downloadTask.taskIdentifier) is \(progressPercentage)% complete...")
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
if let error = error
print("Task failed with error: \(error)")
else
print("Task completed successfully.")
我也在我的 AppDelegate 中添加了这个方法:
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void)
DownloadManager.shared.backgroundSessionCompletionHandler = completionHandler
// if the app gets terminated, I need to reconstruct the URLSessionConfiguration and the URLSession in order to "re-connect" to the previous URLSession instance and process the completed download tasks
// for now, I'm just putting the app in the background (not terminating it) so I've commented out the lines below
//let config = URLSessionConfiguration.background(withIdentifier: identifier)
//let session = URLSession(configuration: config, delegate: DownloadManager.shared, delegateQueue: OperationQueue.main)
// since my app hasn't been terminated, my existing URLSession should still be around and doesn't need to be re-created
let session = DownloadManager.shared.session
session.getTasksWithCompletionHandler (dataTasks, uploadTasks, downloadTasks) -> Void in
// downloadTasks = [URLSessionDownloadTask]
print("There are \(downloadTasks.count) download tasks associated with this session.")
for downloadTask in downloadTasks
print("downloadTask.taskIdentifier = \(downloadTask.taskIdentifier)")
最后,我像这样开始我的测试下载:
let session = DownloadManager.shared.session
// this is a 100MB PDF file that I'm using for testing
let testUrl = URL(string: "https://scholar.princeton.edu/sites/default/files/oversize_pdf_test_0.pdf")!
let task = session.downloadTask(with: testUrl)
// I think I'll ultimately need to persist the session ID, task ID and a file path for use in the delegate methods once the download has completed
task.resume()
当我运行此代码并开始下载时,我看到委托方法被调用,但我还看到一条消息:
A background URLSession with identifier com.example.testapp.background already exists!
我认为这是因为 application:handleEventsForBackgroundURLSession:completionHandler:
中的以下调用而发生的let session = DownloadManager.shared.session
我的 DownloadManager 类中的 session 属性的 getter(我直接从前面引用的博客文章中获取)总是尝试使用后台配置创建一个新的 URLSession。据我了解,如果我的应用程序已被终止,那么这将是“重新连接”到原始 URLSession 的适当行为。但是由于可能应用程序没有被终止,而只是进入后台,所以当调用 application:handleEventsForBackgroundURLSession:completionHandler: 时,我应该引用现有的 URLSession 实例。至少我认为这就是问题所在。谁能为我澄清这种行为?谢谢!
【问题讨论】:
单独构造 URLSession 对象是否足以重新连接到前一个实例,或者我们必须恢复该会话上的任何任务,如本论坛中讨论的 forums.developer.apple.com/thread/77666 【参考方案1】:您的问题是每次引用会话变量时都在创建一个新会话:
var session : URLSession
get
let config = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).background")
return URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
相反,将会话保留为实例变量,然后获取它:
class DownloadManager:NSObject
static var shared = DownloadManager()
var delegate = DownloadManagerSessionDelegate()
var session:URLSession
let config = URLSessionConfiguration.background(withIdentifier: "\(Bundle.main.bundleIdentifier!).background")
override init()
session = URLSession(configuration: config, delegate: delegate, delegateQueue: OperationQueue())
super.init()
class DownloadManagerSessionDelegate: NSObject, URLSessionDelegate
// implement here
当我在操场上这样做时,它表明重复调用会产生相同的会话,并且没有错误:
会话不在进程中,它是操作系统的一部分。每次访问写入的会话变量时都会增加引用计数,这会导致错误。
【讨论】:
如果您使 URLSession 无效并且必须创建一个新的怎么办? 那么当使用单个 URLSession 执行多个任务时,如何识别一个任务呢? @francisaugusto 该任务有一个taskIdentifier
属性。您可以在创建任务时将其存储在某个地方,并在以后使用它来识别它...以上是关于URLSession downloadTask 在后台运行时的行为?的主要内容,如果未能解决你的问题,请参考以下文章
URLSession 没有返回位置数据(session:downloadTask:didFinishDownloadingToURL 位置)
URLSession downloadTask 比互联网连接慢得多