In iOS's Background Tasks framework, what must a launch handler do with expirationHandler and setTaskCompleted(success:), and what breaks when either is missing?
answer
- a stop signal and a done signal
- it may arrive early
- every exit path, exactly once
- false reports failure, it does not retry
basics
~20 sAssign expirationHandler to cancel the work quickly, and call setTaskCompleted(success:) exactly once when the work ends on any path. Without a handler the system marks the task failed; without completion the app burns its time and may be killed.
solid answer
~40 sThe `BGTask` a launch handler receives is a contract. `expirationHandler` is the stop signal: the system calls it shortly before the background time runs out, possibly early when conditions change, for example when the person starts using the device during a processing task. It should cancel the work fast and make sure the task gets completed. `setTaskCompleted(success:)` is the done signal, called once on every exit path, so the system can suspend the app. With no `expirationHandler`, the header says the system marks the task complete and unsuccessful instead of warning the app. Never calling `setTaskCompleted` keeps the app running until its time is used up, wasting battery, and may get it killed. `success: false` reports failure but doesn't retry; to try again, submit a new request first.
code
swift · 33 linesimport BackgroundTasks
enum CacheCleanup {
nonisolated static let identifier = "com.example.podcasts.cache-cleanup"
nonisolated static func schedule() async {
let request = BGProcessingTaskRequest(identifier: identifier)
request.requiresExternalPower = true
do {
if #available(iOS 27, *) {
try await BGTaskScheduler.shared.submitTaskRequest(request)
} else {
try BGTaskScheduler.shared.submit(request)
}
} catch {
print("Cache cleanup not scheduled: \(error)")
}
}
// Registered for `identifier` during launch; the task arrives here.
nonisolated static func handle(_ task: BGProcessingTask) {
let cleanup = Task {
await schedule() // the next run, or a retry if this one stops early
// App-defined: deletes played episodes, checks Task.isCancelled
// between files, and returns false if it stopped early.
let finished = await DownloadCache.prunePlayedEpisodes()
task.setTaskCompleted(success: finished) // the single completion call
}
task.expirationHandler = {
cleanup.cancel() // stop now; the work returns and completes the task
}
}
}go deeper
Recall the two members of a BGTask: expirationHandler to stop when told, and setTaskCompleted(success:) to report that the work ended.
Explain when the handler fires, including early on condition changes, why the work must be cancellation-aware, and why completion belongs on every exit path exactly once.
Show the production failures: missing handlers marked unsuccessful, completion too late after ignored cancellation, completion too early, and retries nobody submitted, plus how you test the expiry path.
Set the team pattern for every background handler: one wrapper that resubmits, cancels on expiry, checkpoints progress and completes once, so each feature cannot get the contract wrong.
## The task object is a contract When iOS launches an app for a background task, the launch handler receives a **`BGTask`**: a `BGAppRefreshTask`, a `BGProcessingTask` or another subclass. Two of its members carry the contract. **`expirationHandler`** is the closure the system calls when the app must stop. **`setTaskCompleted(success:)`** is the call that tells the system the work is over. The system lends the app runtime; the app promises to stop when asked and to say when it is done. ## expirationHandler: the stop signal From the `BGTask` header: - The system calls the handler "shortly before the task's background time expires", and it "may be called before the background process uses the full amount of its allocated time" when system conditions change. - For a **processing task**, the plainest such change is the person picking up the device: the header says the system terminates any running processing task when the user starts using the device. - The handler should **cancel ongoing work**, do any cleanup "in as short a time as possible", and make sure **`setTaskCompleted(success:)`** is then called. - The system clears the property after calling it, or once `setTaskCompleted(success:)` is called, to limit the retain cycle a closure that captures the task would create. - **Not setting a handler at all** makes the system mark the task "complete and unsuccessful instead of sending a warning". The app loses its one chance to stop cleanly. ## setTaskCompleted(success:): the done signal - Call it **as soon as the work ends, on every path**: success, a thrown error, cancellation, and an early `guard` that bails out. - If it is never called, the header says the system keeps the app running in the background until all the available time is consumed, "wasting battery power", and that not calling it before the time expires "may result in the system killing your app". - The system suspends the app as soon as all its background tasks are complete, so a prompt call is also how the app gets out of the way. - **`success: false` is a report, not a retry.** To try again, the header suggests submitting a new task request before calling the method. ## Wiring it with Swift concurrency In a podcast app, a processing task deletes played episodes from the download cache while the phone charges. The work runs in a Swift `Task`. The expiration handler cancels that `Task`; the work checks for cancellation between files, returns early, and the single completion call reports the result: ```swift nonisolated static func handle(_ task: BGProcessingTask) { let cleanup = Task { await schedule() // next run, or a retry let finished = await DownloadCache.prunePlayedEpisodes() task.setTaskCompleted(success: finished) } task.expirationHandler = { cleanup.cancel() } } ``` What makes this correct: 1. **The next request is submitted first**, so an expired or failed run still leaves one scheduled. 2. **There is one completion call site**, at the end of the work, and the expiry path reaches it because cancellation makes the work return. Keeping a single call site is the simplest way to complete exactly once. 3. **The work is cancellation-aware.** Cancelling a Swift `Task` only marks it cancelled; a loop that never checks keeps running past the warning, and the completion call arrives too late. 4. **Long work saves progress.** If the pruning can be cut off, it should record where it stopped so the next run continues instead of starting over. The same shape works without Swift concurrency: whatever runs the work, the expiration handler stops it, and the work's own exit path reports the outcome once. ## Failure modes at a glance | Mistake | What happens | |---|---| | No `expirationHandler` | The system marks the task complete and unsuccessful, with no warning | | Handler set, but the work ignores cancellation | Completion arrives late; the app may be killed | | `setTaskCompleted(success:)` never called | The app runs until its time is gone, wasting battery, and may be killed | | Called before the async work finishes | The system can suspend the app with the work half done | | `success: false` with no new request | Nothing tries again until something else submits | ## Testing the stop path The expiry path is the one that never runs on a developer's desk. On a device, the debugger can launch a task and then force its expiration, which calls the `expirationHandler` so you can watch the work stop and the task complete. How long a background run may last and how to design work that finishes across runs belongs to the mobile system design material on background limits; the contract above is what the framework itself asks of the code.
- With BGTaskScheduler, why can calling setTaskCompleted(success: true) right after starting async work in the launch handler lose that work?The header says the system suspends the app as soon as all background tasks are complete. Completing before the async work finishes tells the system the app is done, so it can be suspended mid-write. Complete only when the work actually ends.
- Why is it safe for a BGTask's expirationHandler closure to capture the task itself?The header says the system clears `expirationHandler` after calling it or once `setTaskCompleted(success:)` is called, precisely to break the retain cycle that capturing the task inside the closure would create.
- How do you make a processing task that is regularly stopped early still finish its job?Make each unit of work small and record progress, such as the last file deleted, so the next run resumes. Submit the next request at the start of each run. The design of work that completes across many runs is covered with background limits in mobile system design.
- The expirationHandler fires only after the full allotted time is used up
- Once the expirationHandler runs the system completes the task itself, so no completion call is needed
- Leaving expirationHandler nil is fine when the work is usually quick
- setTaskCompleted(success: false) makes the system retry the task automatically
- Call setTaskCompleted as soon as the async work has been started