【问题标题】:Which is the best way to test a background URLSession?测试后台 URLSession 的最佳方法是什么?
【发布时间】: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 并实现了它的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 和应用程序委托的 handleEventsForBackgroundURLSession 方法是否被调用。可能是因为下载太快看不到这个。

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

【问题讨论】:

  • 我在我的大多数系统中都使用后台通信/下载:我大量使用控制台调试语句以及实际手机的日志记录。老派,但它有效。

标签: ios swift3 background-process nsurlsession nsurlsessiondownloadtask


【解决方案1】:

在 Appdelegate 的 BackgroundFetch 上调用此方法 downloadImage

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

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

【讨论】:

  • 谢谢,但实际上这样我并没有完全测试我想要的东西,对吧?在我遵循的使用后台 URL 会话的示例中,Background fetch 功能未启用...也许示例错误?
  • 您可以启用它进行健全性测试,然后可以删除该功能。这只是为了确认该功能是否在后台运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2020-12-25
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
相关资源
最近更新 更多