How track download progress in swift?

Kanan Abilzada
2 min readJan 2, 2022

--

Tracking download process with URLSessionDownloadTask

In this tutorial, I’ll explain tracking any download task in swift. We will use URLSessionDownloadTask for this. I will create an application that downloads pdf and we will show progress in UIProgressView. Let’s get started.

Firstly, create a new project and create DownloadTask class. And add this line of codes on there:

Okay, let’s explain these codes:

We used URLSessionConfiguration.background(withIdentifier: “backgroundTasks”), and as per Apple’s documentation:

A session configured with this object hands control of the transfers over to the system, which handles the transfers in a separate process. In iOS, this configuration makes it possible for transfers to continue even when the app itself is suspended or terminated.

And we created a new session with this configuration.

We added URLSessionDownloadDelegate and added two functions, the first function is calculating of download completion of the task:

func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
self.totalDownloaded = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)}

the second function is triggering when the task was completed:

func urlSession(_ session: URLSession,downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {    print("downloaded")}

Okay, I created totalDownloaded variable and it will change in the first delegate function. In our ViewController, we bind to the handleDownloadedProgressPercent function. I added its bind function on download function:

func download(url: String, progress: ((Float) -> Void)?) {
/// bind progress closure to View
self.handleDownloadedProgressPercent = progress
...
}

In your ViewController:

class ViewController: UIViewController {// MARK: - Views
private
lazy var progressView: UIProgressView = {
let progressView = UIProgressView()
progressView.frame = .zero
return progressView
}()
// MARK: - Properties
var
downloadTask: DownloadTask!
// MARK: - Main methods
override
func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.addSubview(progressView)
progressView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width - 20,
height: 40)
progressView.center = view.center

/// load downloadTask
downloadTask = DownloadTask()
downloadTask.download(url: "https://publications.gbdirect.co.uk/c_book/thecbook.pdf") { [weak self] totalDownloaded in
print(totalDownloaded)
self?.progressView.progress = totalDownloaded
}
}
}

Okay, our ViewController is ready now :)

Conclusion

So, we learned how to track any task’s progress in swift. For more details click here. Thank you for reading :)

--

--