skip to content

With a background URLSession, how does an iOS transit app download offline timetable packs overnight and handle being relaunched when they finish?

level: seniorimportance: should knowfreq 46%

answer

  1. transfers run in another process
  2. same identifier after relaunch
  3. store the app delegate's handler
  4. file vanishes when the callback returns

basics

~20 s

Create the session from URLSessionConfiguration.background(withIdentifier:) with a delegate, start download tasks, and let the system transfer them. On relaunch, recreate the session with the same identifier, move each file in didFinishDownloadingTo, and call the stored completion handler after urlSessionDidFinishEvents.

solid answer

~40 s

I create one session from `URLSessionConfiguration.background(withIdentifier:)` with a fixed identifier, `isDiscretionary = true` for overnight packs, and a delegate, because background sessions deliver events only through a delegate. Download tasks are handed to a system process and continue while the app is suspended or terminated by the system. When they finish, iOS wakes or relaunches the app and calls `application(_:handleEventsForBackgroundURLSession:completionHandler:)`; I store that handler and make sure the session exists again with the same identifier. The delegate then gets `urlSession(_:downloadTask:didFinishDownloadingTo:)`, where I must move the file before returning because it is deleted afterwards, and finally `urlSessionDidFinishEvents(forBackgroundURLSession:)`, where I call the stored handler on the main queue. If the user force-quits the app, the system cancels those transfers.

code

swift · 43 lines
swift
import UIKit

final class TimetableDownloader: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
    static let shared = TimetableDownloader()
    var backgroundCompletionHandler: (() -> Void)?

    lazy var session: URLSession = {
        let config = URLSessionConfiguration.background(withIdentifier: "com.example.transit.timetables")
        config.isDiscretionary = true
        config.sessionSendsLaunchEvents = true
        return URLSession(configuration: config, delegate: self, delegateQueue: nil)
    }()

    func schedulePack(_ url: URL) {
        let task = session.downloadTask(with: url)
        task.countOfBytesClientExpectsToReceive = 40 * 1024 * 1024
        task.resume()
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
                    didFinishDownloadingTo location: URL) {
        // The file is deleted when this method returns: move it now.
        let dest = URL.applicationSupportDirectory.appending(path: "pack.zip")
        try? FileManager.default.removeItem(at: dest)
        try? FileManager.default.moveItem(at: location, to: dest)
    }

    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        DispatchQueue.main.async {
            self.backgroundCompletionHandler?()
            self.backgroundCompletionHandler = nil
        }
    }
}

final class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication,
                     handleEventsForBackgroundURLSession identifier: String,
                     completionHandler: @escaping () -> Void) {
        TimetableDownloader.shared.backgroundCompletionHandler = completionHandler
        _ = TimetableDownloader.shared.session // recreate with the same identifier
    }
}

go deeper

for a junior

Recall that background(withIdentifier:) creates a session whose downloads continue while the app is suspended, and that it needs a delegate.

for a middle

Explain the supported task types, why the file must be moved inside didFinishDownloadingTo, and what isDiscretionary and sessionSendsLaunchEvents control.

for a senior

Walk the relaunch order: the app delegate call, recreating the session with the same identifier, per-task callbacks, then urlSessionDidFinishEvents and the handler on the main queue.

for a principal

Weigh which transfers deserve the system's background machinery, given force-quit cancellation and the rate limiter, and keep the app to one well-owned background session.

## What a background session is A **background session** is a `URLSession` created from `URLSessionConfiguration.background(withIdentifier:)`. Its uploads and downloads are handed to a system process, so they continue while the app is suspended and even after the system terminates it. `URLSession` and the original `backgroundSessionConfiguration(_:)` arrived in iOS 7; that method was deprecated in iOS 8 in favour of `background(withIdentifier:)`. A transit app uses one to fetch offline timetable packs overnight. Scheduling the decision of when to refresh content belongs to the Background Tasks framework, covered in its own lesson; the transfer itself is URLSession's job. ## Setting it up 1. Create the configuration with a **fixed identifier**; most apps need only one background session. 2. Set **`isDiscretionary = true`** for packs that can wait, so the system can choose good conditions such as Wi-Fi and power. Apple notes that a transfer started while the app is in the background is treated as discretionary anyway. 3. Leave **`sessionSendsLaunchEvents`** at its default `true`, so the system wakes or launches the app when tasks finish or need authentication. 4. Create the session with a **delegate** that adopts `URLSessionDownloadDelegate`. 5. Create tasks with `downloadTask(with:)`, optionally set `earliestBeginDate` (iOS 11) and `countOfBytesClientExpectsToReceive`, and call `resume()`. ## What background sessions do not support | Limitation | Consequence | |---|---| | A delegate is required for event delivery | completion-handler and `await`-style results have no reliable place to land after the process ends | | Data tasks are not supported | use download tasks, or upload tasks from a file | | Uploads must come from a file | uploads from `Data` or a stream fail after the app exits | | Only HTTP and HTTPS | no custom `URLProtocol` | | Redirects are always followed | `willPerformHTTPRedirection` is not called | | `waitsForConnectivity` is ignored | background sessions always wait for connectivity | | `urlCache` is `nil` by default | nothing is cached | Timeouts behave differently too: the header for `timeoutIntervalForRequest` says background upload and download tasks are retried automatically after a timeout, so `timeoutIntervalForResource`, seven days by default, is the bound on how long the system keeps trying. ## The relaunch sequence When the packs finish and the app is not running in the foreground: 1. The system resumes the app, or relaunches it in the background if it had been terminated, and calls the app delegate's **`application(_:handleEventsForBackgroundURLSession:completionHandler:)`** with the session identifier. Store the completion handler; do not call it yet. 2. If the app was relaunched, **recreate the session with the same identifier** during launch so the system can reattach the pending tasks to it. A different identifier creates a different, empty session. 3. The delegate receives **`urlSession(_:downloadTask:didFinishDownloadingTo:)`** for each task. The header says the file at `location` is removed when this method returns, so move it now, for example into Application Support. `urlSession(_:task:didCompleteWithError:)` follows. 4. When all queued events are delivered, the session delegate gets **`urlSessionDidFinishEvents(forBackgroundURLSession:)`**. That is the moment to call the stored handler. Apple's article notes this callback may arrive on a secondary queue, and the handler came from UIKit, so call it on the main queue. `application(_:handleEventsForBackgroundURLSession:completionHandler:)` lives on `UIApplicationDelegate` and carries no deprecation in the iOS 27.1 SDK, so even a scene-based app implements it in its app delegate. ## Force-quit and the rate limiter - If the **user** swipes the app away in the app switcher, the system cancels all of that session's background transfers and does not relaunch the app for them; the user must open it again. The cancellation error carries a reason, readable in Swift as `URLError`'s `backgroundTaskCancelledReason`, with `.userForceQuitApplication` among its values. Normal termination by the system does not cancel the transfers. - The system applies a **rate limiter** to background launches: a download started while the app is in the background begins only after a delay that grows each time the app is resumed or relaunched. Batch many tasks in one session instead of chaining one download per wake-up. The delay resets when the user brings the app to the foreground. ## Common defects in review - Creating the background session lazily only when a screen opens, so a relaunched app never recreates it and its events are never delivered. - Reading the downloaded file asynchronously after `didFinishDownloadingTo` has returned, when it is already gone. - Calling the app delegate's completion handler immediately, before the session has delivered its events. - Starting one background session per pack, which multiplies overhead and fights the rate limiter.

  • Why does each pack the app starts from a background wake-up begin later and later?
    The system rate-limits background launches. A task started while the app is in the background does not begin until a delay expires, and that delay grows each time the system resumes or relaunches the app. Start all packs together in one session, and the delay resets when the user foregrounds the app.
  • A widget extension wants to start a background download; what must its session configuration set?
    Set `sharedContainerIdentifier` to an app group container shared with the main app, because the system writes downloaded files there. The header warns that a URL session created from an app extension without a valid value for this property is invalidated upon creation.
  • How can the app tell that a pack failed because the user force-quit it?
    The task completes with a cancellation error whose user info carries the background cancellation reason. In Swift, `URLError`'s `backgroundTaskCancelledReason` returns `.userForceQuitApplication` in that case, distinct from `.backgroundUpdatesDisabled` and `.insufficientSystemResources`, so the app can offer to restart the pack on next launch.

A background session is a parcel depot: you hand over the orders and go to sleep, the depot rings your doorbell when deliveries arrive, and you must unpack each parcel at the door before the courier leaves with it, then sign off once the last one is in.

  • A background session can run ordinary data tasks
  • The downloaded file stays at its temporary location until you move it
  • Background transfers keep going after the user force-quits the app
  • Recreating the session with a new identifier reattaches the old tasks
  • Call the completion handler as soon as handleEventsForBackgroundURLSession arrives
  • waitsForConnectivity must be set to true on a background configuration