To show download progress in a UIProgressView, start a download task with URLSession.shared.downloadTask(with:completionHandler:) and set progressView.observedProgress = task.progress. The bar then follows the task with no buffer or division of your own. When the server doesn't send a Content-Length, countOfBytesExpectedToReceive is -1, so show the bytes received instead of a percentage. The 2019 delegate code divided by that -1, never reset its buffer, and kept its view controller in memory because the session was never invalidated.
SWIFT TIPS · UIKIT · URLSESSION
First posted on July 11, 2019, as "ProgressView Whlle Get Api". Rewritten on November 18, 2026. The download tests were run on a Mac against a local test server on 127.0.0.1 serving 1 MiB of sample bytes, with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1. The view controller was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 and iOS 26.2 as deployment targets, but not run on a device.
In 2019 I wanted a progress bar that fills while an image downloads. The post showed how to add a Progress View in Interface Builder and what its properties do, then two pieces of code: a timer-style demo that fills the bar from 0 to 100 one step per second, and a real download. The download created a URLSession with the view controller as its delegate, appended each piece of data to a buffer, and set the progress to the buffer's length divided by the expected length.
The delegate approach is a valid way to watch a download. The 2019 version had three problems that only show up under certain conditions, so I ran it.
Running the 2019 delegate code
I copied the 2019 delegate code into a plain class, replaced progressView.setProgress(x) with recording x, and pointed it at a local server that sends 1 MiB in 64 KiB pieces, once with a Content-Length header and once without:
1. First tap, server sends Content-Length (1 MiB):
expectedContentLength 1048576, 16 updates, first 0.06, last 1.00
2. Second tap on the same screen:
expectedContentLength 1048576, 16 updates, first 1.06, last 2.00
3. Server streams the file without Content-Length:
expectedContentLength -1, 16 updates, first -65536.00, last -1048576.00
4. Is the delegate freed when nothing else holds it?
expectedContentLength 1048576, 16 updates, first 0.06, last 1.00
after the screen lets go, without invalidating the session: still in memory
after finishTasksAndInvalidate(): freed
- The second tap started at 106%.
bufferwas created once and never emptied, so the second download added to the first and the progress went from 1.06 to 2.00. Apple's documentation says a progress view pins values above 1.0 to 1.0, so the bar would sit full from the first moment. - No
Content-Length, negative progress. When the server streams a response without that header,expectedContentLengthis -1. Apple's documentation forcountOfBytesExpectedToReceivedescribes the same case: without the header, the value is "transfer size unknown". Dividing by -1 gave -65536, then lower, and a progress view pins anything below 0.0 to 0.0, so the bar stays empty. - The screen stayed in memory. Apple's documentation says a session keeps a strong reference to its delegate until the app exits or the session is invalidated, and that not invalidating it leaks memory. The 2019 code made a new session on every tap and never invalidated one. In the test, the delegate stayed alive until I called
finishTasksAndInvalidate().
The 2019 code also loaded http://i.stack.imgur.com/b8zkg.png, a plain-HTTP address. App Transport Security blocks plain HTTP connections from apps by default, so that URL needed an exception in Info.plist to load at all.
What a download task's Progress does
Every URLSessionTask has a progress object. I watched it for the same two downloads:
1. Server sends Content-Length:
completion handler read 1048576 bytes from the temporary file
progress.fractionCompleted: 17 updates: 0.05, 0.11, 0.17 ... 0.94, 1.00
countOfBytesExpectedToReceive while downloading: [1048576]
2. Server streams without Content-Length:
completion handler read 1048576 bytes from the temporary file
progress.fractionCompleted: 18 updates: 0.05, 0.06, 0.07 ... 0.20, 1.00
countOfBytesExpectedToReceive while downloading: [-1]
With a Content-Length, the fraction rose steadily to 1.00. Without one, it never went negative: it crept up slowly and jumped to 1.00 at the end, and countOfBytesExpectedToReceive stayed at -1 the whole time. So the bar is safe in both cases, and the -1 is the signal to show a byte count instead of a percentage.
A download screen with a progress bar
import UIKit
final class DownloadViewController: UIViewController {
private let progressView = UIProgressView(progressViewStyle: .default)
private let statusLabel = UILabel()
private let imageView = UIImageView()
private let downloadButton = UIButton(configuration: .filled())
private var task: URLSessionDownloadTask?
private var bytesObservation: NSKeyValueObservation?
// HTTPS: App Transport Security blocks plain http:// loads unless the app adds an exception.
private let fileURL = URL(string: "https://example.com/large-image.png")!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
statusLabel.font = .preferredFont(forTextStyle: .footnote)
statusLabel.textColor = .secondaryLabel
imageView.contentMode = .scaleAspectFit
downloadButton.configuration?.title = "Download"
downloadButton.addAction(UIAction { [weak self] _ in self?.startDownload() }, for: .touchUpInside)
let stack = UIStackView(arrangedSubviews: [progressView, statusLabel, downloadButton, imageView])
stack.axis = .vertical
stack.spacing = 12
stack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stack)
NSLayoutConstraint.activate([
stack.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
stack.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 24),
imageView.heightAnchor.constraint(equalToConstant: 240),
])
}
private func startDownload() {
task?.cancel()
statusLabel.text = "Starting..."
imageView.image = nil
let task = URLSession.shared.downloadTask(with: fileURL) { [weak self] location, response, error in
// A cancelled task (a second tap, or leaving the screen) ends here with URLError.cancelled.
if (error as? URLError)?.code == .cancelled { return }
// location points to a temporary file, so read it now rather than keeping the URL.
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
let data = location.flatMap { try? Data(contentsOf: $0) }
let failure = error?.localizedDescription
Task { @MainActor in self?.finish(data: data, status: status, failure: failure) }
}
// The bar follows the task's own Progress object: no buffer, no division, nothing to reset.
progressView.observedProgress = task.progress
// countOfBytesExpectedToReceive is -1 when the server doesn't send Content-Length.
bytesObservation = task.observe(\.countOfBytesReceived) { [weak self] task, _ in
let received = task.countOfBytesReceived
let expected = task.countOfBytesExpectedToReceive
Task { @MainActor in self?.showBytes(received, of: expected) }
}
self.task = task
task.resume()
}
private func showBytes(_ received: Int64, of expected: Int64) {
let done = ByteCountFormatter.string(fromByteCount: received, countStyle: .file)
if expected > 0 {
let total = ByteCountFormatter.string(fromByteCount: expected, countStyle: .file)
statusLabel.text = "\(done) of \(total)"
} else {
statusLabel.text = "\(done) downloaded"
}
}
private func finish(data: Data?, status: Int, failure: String?) {
bytesObservation = nil
task = nil
if let failure {
statusLabel.text = failure
} else if (200..<300).contains(status), let data, let image = UIImage(data: data) {
imageView.image = image
statusLabel.text = "Done"
} else {
statusLabel.text = "The download failed (status \(status))."
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if isMovingFromParent || isBeingDismissed { task?.cancel() }
}
}
How it works
observedProgressdrives the bar. Apple's documentation says that once it's set, the progress view updates its value from theProgressobject by itself, with animation. There is no buffer to reset and nothing to divide.- The shared session.
URLSession.sharedhas no delegate, so nothing holds on to the view controller. The completion handler capturesselfweakly. - The label handles unknown sizes. Observing
countOfBytesReceivedgives the bytes so far. When the expected size is -1, the label shows only the amount downloaded so far, instead of "x of y". - Read the file in the handler. A download task writes to a temporary file and passes its
location. The handler reads the data right away instead of keeping the URL. - Cancelled tasks end quietly. A second tap cancels the first download, and leaving the screen cancels the current one. The handler returns early on
URLError.cancelledso a cancelled download doesn't show an error or clear the new one.
A quick check for your project
- Search for
expectedContentLengthand check what happens when it's -1. - Search for
URLSession(configuration:withdelegate: self. Every such session needsfinishTasksAndInvalidate()orinvalidateAndCancel()when the screen is done with it. - Tap your download button twice in a row and watch the bar. It should start from zero both times.
What the 2019 version said
The original listed the progress view's appearance properties: progressTintColor for the filled part, trackTintColor for the rest, the default and bar styles, and trackImage and progressImage to use images instead of colors. It showed the Object Library search and the Attributes inspector, and included a screen recording:


Keep reading on JR Devhub
Comments