1
我正在使用URLSession dataTask來下載帶有URLSessionDownloadDelegate作爲結果處理程序的文件。但是,從來沒有調用urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
。相反,我得到urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
與錯誤爲零。當使用completionHandler方法來執行任務時,一切正常。URLSession委託成功方法未調用,但沒有錯誤
這裏是我的代碼:
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()
}
}
模擬器輸出
session: task: didCompleteWithError: nil
session: didBecomeInvalidWithError: nil
預先感謝您。
無論是或使用數據任務正確的委託方法和自己積累的數據。無論哪種方式。 – dgatwood
謝謝你,工作!不過,使用「URLSessionConfiguration」的背景並不是必須的。 – MasterCarl