我尝试使用URLSessionDownloadDelegate打印下载进度,但是委托的方法不起作用 尽管图像已下载,但进度不会打印
我有按钮
@IBAction func downloadTapped(_ sender: UIButton) {
let image = "https://neilpatel-qvjnwj7eutn3.netdna-ssl.com/wp-content/uploads/2016/02/applelogo.jpg"
guard let url = URL(string: image) else {return}
let operationQueue = OperationQueue()
let session = URLSession(configuration: .default, delegate: self, delegateQueue: operationQueue)
session.downloadTask(with: url) { (data, response, error) in
guard let url = data else {return}
do {
let data = try Data(contentsOf: url)
OperationQueue.main.addOperation {
self.imageView.image = UIImage(data: data)
}
} catch {
}
}.resume()
}
扩展名
extension DownloadingViewController: URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("=====FINISH=====")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(bytesWritten) / Float(totalBytesWritten)
print(progress)
}
}
一无所有
答案 0 :(得分:2)
您正在呼叫
session.downloadTask(with: url) { (data, response, error) in
这意味着URLSession的delegate
将被忽略,因为下载任务有一个完成处理程序,它被用来代替。因此,您所看到的是预期的行为。
如果您想使用代表,请致电
session.downloadTask(with: url)
并在委托中进行一切,包括接收下载的文件。
另一方面,如果您的目标只是显示进度,则不需要委托。为此,下载任务出售progress
对象。示例:
let task = session.downloadTask(with:url) { fileURL, resp, err in
// whatever
}
// self.prog is a UIProgressView
self.prog.observedProgress = task.progress
task.resume()