1

i try to print progress of downloading using URLSessionDownloadDelegate, but delegate's methods don't work Although image is download, progress don't print

I have button

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

    }

And extension

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

}

nothing at all

1 Answer 1

3

You are calling

session.downloadTask(with: url) { (data, response, error) in

This means that the URLSession's delegate is ignored, because the download task has a completion handler which is used instead. So what you are seeing is the expected behavior.


If you wish to use a delegate, call

session.downloadTask(with: url)

and do everything in the delegate, including receiving the downloaded file.


On the other hand, if your goal is merely to display progress, there is no need for the delegate. The download task vends a progress object for this purpose. Example:

    let task = session.downloadTask(with:url) { fileURL, resp, err in
        // whatever
    }
    // self.prog is a UIProgressView
    self.prog.observedProgress = task.progress
    task.resume()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.