首页 > 解决方案 > 为什么 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)
    }

}

什么都没有

标签: swiftdelegatesurlsession

解决方案


你在打电话

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()

推荐阅读