【发布时间】:2017-05-27 14:36:14
【问题描述】:
我正在按照示例代码下载几张图片并在单元格中显示它们。为此,我配置了一个URLSession,如下所示:
let backgroundConfig = URLSessionConfiguration.background(withIdentifier: "com.myexample.images")
self.backgroundSession = URLSession(configuration: backgroundConfig, delegate: self, delegateQueue: nil)
然后,我执行这样的图像下载:
func downloadImage(imageUrl url: URL, imageId: Int, completion: ImageResult?) -> URLSessionDownloadTask? {
let request = URLRequest(url: url)
let task = backgroundSession.downloadTask(with: request)
// Code here to keep track of the completion handler for this task
task.resume()
return task
}
我也符合URLSessionDownloadDelegate 并实现了它的didCompleteWithError、didFinishDownloadingTo 和urlSessionDidFinishEvents 方法。对于最后一种方法,我有这个实现:
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let completionHandler = appDelegate.backgroundSessionCompletionHandler {
appDelegate.backgroundSessionCompletionHandler = nil
completionHandler()
}
}
然后在AppDelegate:
var backgroundSessionCompletionHandler: (() -> Void)?
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
backgroundSessionCompletionHandler = completionHandler
}
我不知道这是否真的有效。我在模拟器中运行该应用程序,我转到手机的主页以将应用程序置于后台状态,但我无法查看 urlSessionDidFinishEvents 和应用程序委托的 handleEventsForBackgroundURLSession 方法是否被调用。可能是因为下载太快看不到这个。
我怎样才能在模拟器中正确测试呢?我错过了什么吗?
【问题讨论】:
-
我在我的大多数系统中都使用后台通信/下载:我大量使用控制台调试语句以及实际手机的日志记录。老派,但它有效。
标签: ios swift3 background-process nsurlsession nsurlsessiondownloadtask