Ich verwende eine URLSession dataTask, um eine Datei mit einem URLSessionDownloadDelegate als Ergebnishandler zu downloaden. urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
wird jedoch nie aufgerufen. Stattdessen erhalte ich urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
mit dem Fehler, der Null ist. Wenn Sie stattdessen die CompletionHandler-Methode zum Ausführen der Aufgabe verwenden, funktioniert alles.URLSession Delegate Erfolg Methoden nicht aufgerufen, aber kein Fehler
Hier ist mein Code:
import UIKit
class ViewController: UIViewController, URLSessionDownloadDelegate {
var downloadTask: URLSessionDataTask?
override func viewDidLoad() {
super.viewDidLoad()
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
let url = URL(string: "https://unsplash.it/200/300/?random")!
//downloadTask = session.dataTask(with: request)
downloadTask = session.dataTask(with: url)
downloadTask!.resume()
}
@IBAction func cancelButtonTapped(_ sender: Any) {
downloadTask?.cancel()
}
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
print("session: didBecomeInvalidWithError: \(error?.localizedDescription)")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("Your data is here!")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten/totalBytesExpectedToWrite)
print("Making progress: \(progress)")
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print("session: task: didCompleteWithError: \(error?.localizedDescription)")
session.finishTasksAndInvalidate()
}
}
Der Simulator Ausgang ist
session: task: didCompleteWithError: nil
session: didBecomeInvalidWithError: nil
Vielen Dank im Voraus.
Entweder das oder die richtigen Delegatmethoden für eine Daten Aufgabe verwenden und die Daten selbst ansammeln. In jedem Fall. – dgatwood
Danke, das hat funktioniert! Es war jedoch nicht notwendig, den Hintergrund für 'URLSessionConfiguration' zu verwenden. – MasterCarl