1
我正在嘗試向我的應用添加後臺獲取功能。目前,委託功能urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
稱爲網絡調用完成後,但在高速緩存目錄中的網址不存在:無法從URLSessionTaskDelegate獲取數據
class DownloadManager: NSObject, URLSessionTaskDelegate, URLSessionDownloadDelegate {
static var shared = DownloadManager()
var session : URLSession {
get {
let config = URLSessionConfiguration.background(withIdentifier: "my_Identifier")
return URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print(location.absoluteString)
do {
let myData = try Data(contentsOf: location)
} catch let error {
print(error.localizedDescription)
// The The file 「file_id.tmp」 couldn’t be opened because there is no such file.
}
}
public func fetch() {
guard let url = URL(string: "#{myURL}") else {
return
}
let task = session.downloadTask(with: url)
task.resume()
}
}
而且在我的應用程序代表:
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("Executing background fetch")
DownloadManager.shared.fetch()
completionHandler(.newData)
}
我在想什麼?
當我嘗試它時,你的代碼似乎工作。您的網址可能是以'http'而不是'https'開頭的嗎?這可能會使其與App Transit Security發生衝突。 –
他們都是'https'。你如何模擬這個背景獲取? –
我剛剛將您的課程複製到CodeRunner中,將URL替換爲我網站上的文件,並在底部添加一行以調用'DownloadManager.shared.fetch()'。它似乎正確下載。 –