swift - 为什么 URLSession 不在 URLSessionDownloadDelegate 中?
问题描述
我尝试使用 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)
}
}
什么都没有
解决方案
你在打电话
session.downloadTask(with: url) { (data, response, error) in
这意味着 URLSessiondelegate
被忽略,因为下载任务有一个完成处理程序,它被使用。所以你看到的是预期的行为。
如果您想使用委托,请致电
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()
推荐阅读
- python-3.x - 是否可以用字典列表映射列表
- java - 如何将过渡动画(淡入、淡出)从 jframe 更新到另一个 jframe?
- linux - 致命错误:kdecoration.h:没有这样的文件或目录
- asp.net-core-mvc - 想要一个通用的 EnterpriseLibrary for .NET Core MVC(通用数据库文件)
- go - 切片索引奇怪的边缘情况
- javascript - 基于另一个对象的值访问对象的属性
- scala - 带有 postfixOps 的 Scala 映射
- javascript - 在 React 中为嵌套组件导出 Hooks?
- batch-file - 用于启动新 javaw 进程的批处理文件未按预期工作
- go - 如何在golang的x509证书中解码复合自定义扩展?使用当前代码错误是:asn1:结构错误:序列标签不匹配