哪个是测试后台URLSession的最佳方法?

时间:2017-05-27 14:36:15

标签: ios swift3 background-process nsurlsession nsurlsessiondownloadtask

我正在按照示例代码下载多个图像并在单元格中显示它们。为此,我配置了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并实施其didCompleteWithErrordidFinishDownloadingTourlSessionDidFinishEvents方法。对于最后一种方法,我有这个实现:

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或app delegate的handleEventsForBackgroundURLSession方法。也许是因为下载太快而无法看到这一点。

我怎样才能在模拟器中正确测试?我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

在Appdelegate的downloadImage上调用此方法BackgroundFetch

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Swift.Void)

然后在调试模式下,在设备上运行应用,然后锁定手机,然后从XCode - Debug Menu开始,选择Simulate Background Fetch