skip to content

With URLSession, a transit app's vehicle-position stream and an old completion-handler request keep running after the screen closes; how does cancellation reach each, and what error arrives?

level: seniorimportance: should knowfreq 58%

answer

  1. who holds the task alive
  2. Swift Task cancellation bridges only async calls
  3. error code minus 999
  4. filter cancellations out of error UI

basics

~20 s

Cancelling the Swift Task cancels an awaiting data(for:) or bytes(for:) call; a dataTask(with:completionHandler:) task ignores it, so keep that task and call cancel(). Either way a cancellation error, usually URLError .cancelled, arrives and the UI should ignore it.

solid answer

~40 s

URLSession's async methods tie the underlying `URLSessionTask` to the calling Swift `Task`: cancel the Task, for example when the departures screen disappears, and the transfer is cancelled and the call throws, so the `for try await` loop over `bytes(for:).lines` ends. A task made with `dataTask(with:completionHandler:)` is not tied to any Swift Task, and the session keeps a strong reference to it until it finishes, so dropping my reference does nothing; I keep the task and call `cancel()`. That returns at once, and the completion handler or `urlSession(_:task:didCompleteWithError:)` then receives `NSURLErrorCancelled`, which Swift sees as `URLError` with code `.cancelled`. I filter that code, and `CancellationError` from other awaits, out of the error UI, because the user caused it.

code

swift · 46 lines
swift
import Foundation

@MainActor
final class VehicleTracker {
    private var streamTask: Task<Void, Never>?
    private(set) var positions: [String] = []

    func start(feed: URL) {
        streamTask = Task {
            do {
                let (bytes, _) = try await URLSession.shared.bytes(from: feed)
                for try await line in bytes.lines {
                    positions.append(line)
                }
            } catch let error as URLError where error.code == .cancelled {
                // The screen went away: not a failure to show.
            } catch is CancellationError {
                // Cancelled between awaits.
            } catch {
                print("feed failed:", error)
            }
        }
    }

    // Called when the departures screen disappears.
    func stop() {
        streamTask?.cancel()
        streamTask = nil
    }
}

// Legacy completion-handler code: Task cancellation never reaches it.
final class LegacyLoader {
    private var task: URLSessionDataTask?

    func load(_ url: URL) {
        task = URLSession.shared.dataTask(with: url) { _, _, error in
            if let error = error as? URLError, error.code == .cancelled { return }
        }
        task?.resume()
    }

    func stop() {
        task?.cancel() // delivers URLError(.cancelled) to the handler
    }
}

go deeper

for a junior

Recall that a URLSessionTask has cancel() and that a cancelled request reports URLError code .cancelled.

for a middle

Explain that the async methods follow the calling Task's cancellation while completion-handler tasks need their own cancel(), and that the session holds a task alive.

for a senior

Show the lifecycle you would ship: store the handle, cancel on disappear, filter .cancelled and CancellationError from error UI and metrics, and pause downloads with resume data.

for a principal

Discuss which work a screen may cancel and which must outlive it, and how the networking layer exposes cancellation so features cannot forget it.

## Two worlds of cancellation A transit app's departures screen does two kinds of networking. A view model streams vehicle positions with the async `bytes(for:)` API, and an older loader still uses `dataTask(with:completionHandler:)`. When the user leaves the screen, both should stop, but they stop through different routes. - **Swift concurrency cancellation** is cooperative: calling `cancel()` on a Swift `Task` sets a flag that code inside the task must notice. How that works in general is covered in the lesson on tasks and cancellation. - **`URLSessionTask` cancellation** is the URL loading system's own mechanism: calling `cancel()` on the task marks it cancelled and ends the transfer. URLSession's async methods connect the first to the second. The completion-handler API does not. ## How the async methods react The SDK shows the mechanism in the open. The Swift overlay's back-deployed `data(for:)` for iOS 13 and 14 wraps a data task in `withTaskCancellationHandler`, and its cancellation handler calls `cancel()` on that data task. From iOS 15 the native `data(for:delegate:)`, `download(for:delegate:)`, `upload(for:from:delegate:)` and `bytes(for:delegate:)` are implemented inside Foundation and their pages do not describe the internals, but the observable behaviour is the same: cancelling the surrounding Task cancels the transfer and the awaiting call throws. For the vehicle stream that means: 1. `start()` stores the `Task` that awaits `bytes(from:)` and iterates `bytes.lines`. 2. `stop()`, called when the screen disappears, cancels that Task. 3. The URL loading system cancels the underlying data task, the `for try await` loop throws, and the Task finishes. What is thrown is usually `URLError` with code `.cancelled`, the Swift face of `NSURLErrorCancelled` (-999). Code between other awaits may instead throw `CancellationError`, so catch both and treat them as "stopped", not "failed". `URLSession.AsyncBytes` also exposes its `task` if you need the `URLSessionDataTask` itself. ## How completion-handler tasks react `dataTask(with:completionHandler:)` returns a `URLSessionDataTask` and nothing else. Three facts decide its fate: - The session keeps a **strong reference** to the task from `resume()` until the request finishes or fails, so setting your property to `nil` does not stop it. - A Swift Task cancelled around it has no effect, because nothing connects the two. - Calling **`cancel()`** returns immediately and marks the task cancelled; the session then delivers an error in `NSURLErrorDomain` with code `NSURLErrorCancelled` to the completion handler, or to `urlSession(_:task:didCompleteWithError:)` for delegate-based tasks. The header adds that a task may still send some delegate messages before the cancellation is acknowledged. | What you do | Async method | Completion-handler task | |---|---|---| | Cancel the surrounding Swift Task | transfer cancelled, call throws | keeps running | | Drop your reference | dropping a Task handle does not cancel it | keeps running; the session holds it | | Call `cancel()` on the `URLSessionTask` | call throws | handler gets `URLError(.cancelled)` | | `invalidateAndCancel()` on the session | cancelled | cancelled | ## Pausing, closing and stopping everything - A **download task** can be stopped with `cancel(byProducingResumeData:)`, whose resume data, if the server allows it, feeds `downloadTask(withResumeData:)` later. That is the API for pausing a large offline timetable pack; designing resumable uploads for a whole app is a separate system design topic. - A **WebSocket task** (`URLSessionWebSocketTask`, iOS 13) is closed politely with `cancel(with:reason:)`, which sends a close code; a plain `cancel()` sends a cancellation frame without any reason. - A **session** owned by a feature can be shut down with `invalidateAndCancel()`, which cancels every outstanding task, or `finishTasksAndInvalidate()`, which lets them finish. Either way the session cannot create new tasks afterwards. ## What to show the user A cancelled request is the app's own decision, so it must not surface as an alert: - check `(error as? URLError)?.code == .cancelled` in completion handlers; - catch `URLError` with `.cancelled` and `CancellationError` together in async code; - log cancellations at debug level only, so they do not pollute error metrics. When a screen-level cancel should spare some work, such as a payment that must finish, that is a request-pipeline design decision covered with the system design material; at the API level, such work simply should not run inside the Task the screen cancels.

  • How would you let a rider pause a 200 MB offline timetable download and continue it later?
    Call `cancel(byProducingResumeData:)` on the `URLSessionDownloadTask` and keep the returned data. Later, pass it to `downloadTask(withResumeData:)` or `download(resumeFrom:delegate:)`. The resume data is `nil` when the download cannot be resumed, for example when the server does not support it, so the code must fall back to a fresh download.
  • Why can a cancelled delegate-based task still deliver a callback after you called cancel()?
    `cancel()` only marks the task as cancelled and returns; the session completes the task asynchronously. The header says a task may, in some circumstances, send messages to its delegate before the cancellation is acknowledged, so delegate code must tolerate a late `didReceive` before `didCompleteWithError` reports `NSURLErrorCancelled`.

  • Cancelling the Swift Task also stops a dataTask(with:completionHandler:) request
  • Setting the URLSessionDataTask property to nil cancels the request
  • A cancelled data task never calls its completion handler
  • URLSessionTask's cancel() blocks until the connection has closed
  • A URLError with code .cancelled should be shown to the user as a network failure