我在下面的示例代碼下載幾個圖像,並在單元格中顯示它們。對於這一點,我配置的URLSession
這樣的:這是測試背景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
方法。也許是因爲下載速度太快而無法看到。
我該如何在模擬器中正確測試這個?我錯過了什麼嗎?
我使用的背景通信/下載在我的大多數系統中:我使用控制檯調試語句的自由使用以及實際手機的日誌記錄。老派,但它的作品。 – BonanzaDriver