【发布时间】:2018-07-22 16:11:53
【问题描述】:
我可以在后台成功下载文件。 关闭应用并重新打开应用后,仍会按预期下载数据。
但是,为了根据数据下载状态显示 UI,我需要参考实际的后台任务。我特别想知道是否还有一个后台任务正在运行 - 如果是,我需要对这个特定任务的引用。
我该怎么做??
根据我的阅读,这个引用应该由首先配置为后台会话的 downloadSession 自动提供(即self.downloadService.downloadsSession = self.downloadsSession)。但这并没有以某种方式做到这一点......
此外,我通过 a) 按下模拟器中的停止按钮或 b) 通过双击 Home 并将应用程序滑出多线程视图来杀死我的应用程序 --> 这对保持后台任务有效吗?为下一个应用程序启动?? (至少didWriteData 方法在关闭 a) 或 b) 时都会持续触发 - 所以我认为这没问题)
这是我的代码(来自一个更大的项目 - 但你应该明白)...
let downloadService = SomeDownloadService()
lazy var downloadsSession: URLSession = {
let configuration = URLSessionConfiguration.background(withIdentifier: "SomeID.BGSessionConfiguration")
return URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
}()
override func viewDidLoad() {
super.viewDidLoad()
self.downloadService.downloadsSession = self.downloadsSession
// ...file is created somewhere else...
self.downloadService.startDownload(file)
// *** Until here everything OK - file starts downloading in the background *******
// *** HOW DO I GET A REFERENCE TO THE BACKGROUND TASK RUNNING ???????
// ????
// *** KEEPS PRINTING 0 *** WHY ?????????????????????????
print(self.downloadService.activeDownloads.count
}
// Updates progress info
// *** WORKS WELL - upon second App-Start there is still data coming in *******
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
guard let url = downloadTask.originalRequest?.url,
let download = self.downloadService.activeDownloads[url] else {
return
}
download.progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
let totalSize = ByteCountFormatter.string(fromByteCount: totalBytesExpectedToWrite, countStyle: .file)
}
【问题讨论】:
标签: swift background urlsession nsurlsessionconfiguration