0

我在下面的示例代碼下載幾個圖像,並在單元格中顯示它們。對於這一點,我配置的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並執行其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方法。也許是因爲下載速度太快而無法看到。

我該如何在模擬器中正確測試這個?我錯過了什麼嗎?

+0

我使用的背景通信/下載在我的大多數系統中:我使用控制檯調試語句的自由使用以及實際手機的日誌記錄。老派,但它的作品。 – BonanzaDriver

回答

0

通話的appdelegate

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

這種方法downloadImage,然後在調試模式下,運行在設備上的應用程序,然後鎖定您的手機,然後從XCode - Debug Menu,選擇Simulate Background Fetch

+0

謝謝,但實際上這樣我並沒有完全測試我想要的東西,對吧?在我使用後臺URL會話遵循的示例中,「後臺提取」功能未啓用...也許該示例錯誤? – AppsDev

+0

您可以啓用它進行健全性測試,然後可以刪除該功能。只是爲了確認該功能是否在後臺工作。 –

相關問題