With BGTaskScheduler, what must a podcast app register, declare in Info.plist and submit before its episode-list refresh can ever run?
answer
- three places, one identifier string
- an Info.plist array plus a background mode
- before launch finishes, exactly once
- one-shot requests, resubmitted every run
basics
~20 sList the identifier in BGTaskSchedulerPermittedIdentifiers with the fetch background mode, register its launch handler before the app finishes launching, then submit a BGAppRefreshTaskRequest, and submit a fresh one on every run because each request runs once.
solid answer
~40 sThree things must agree on one identifier. Info.plist lists it under `BGTaskSchedulerPermittedIdentifiers`, and `UIBackgroundModes` holds `fetch`, which the Background Modes capability writes. The app calls `BGTaskScheduler.shared.register(forTaskWithIdentifier:using:launchHandler:)` once, before it finishes launching; it returns `false` if the identifier isn't listed, and a second registration of the same identifier kills the app. Then the app submits a `BGAppRefreshTaskRequest`, with `earliestBeginDate` as a "not before" date. On iOS 27 that is `try await BGTaskScheduler.shared.submitTaskRequest(request)`, and the throwing `submit(_:)` is deprecated from iOS 27; an app that still supports older releases keeps `submit(_:)` behind `if #available(iOS 27, *)`. Each request runs once, so the launch handler submits the next one, then refreshes and calls `setTaskCompleted(success:)`. A SwiftUI app can use `.backgroundTask(.appRefresh("id"))` instead of registering, but still declares and submits.
code
swift · 49 linesimport BackgroundTasks
enum EpisodeRefresh {
nonisolated static let identifier = "com.example.podcasts.episode-refresh"
// Call from application(_:didFinishLaunchingWithOptions:) before it returns.
nonisolated static func register() {
let registered = BGTaskScheduler.shared.register(
forTaskWithIdentifier: identifier,
using: nil // nil: a default background queue
) { task in
guard let refresh = task as? BGAppRefreshTask else {
task.setTaskCompleted(success: false)
return
}
handle(refresh)
}
assert(registered, "Identifier missing from BGTaskSchedulerPermittedIdentifiers")
}
nonisolated static func schedule() {
Task.detached(priority: .utility) { // keep submission off the main thread
let request = BGAppRefreshTaskRequest(identifier: identifier)
request.earliestBeginDate = Date(timeIntervalSinceNow: 4 * 60 * 60)
do {
if #available(iOS 27, *) {
try await BGTaskScheduler.shared.submitTaskRequest(request)
} else {
try BGTaskScheduler.shared.submit(request) // deprecated only from iOS 27
}
} catch {
print("Episode refresh not scheduled: \(error)")
}
}
}
nonisolated static func handle(_ task: BGAppRefreshTask) {
schedule() // a request runs once, so queue the next one first
let work = Task {
do {
try await EpisodeFeed.refresh() // app-defined
task.setTaskCompleted(success: true)
} catch {
task.setTaskCompleted(success: false)
}
}
task.expirationHandler = { work.cancel() }
}
}go deeper
Recall the three pieces that share one identifier: the Info.plist list, a launch handler, and a submitted request. Each refresh needs a new request.
Explain the rules behind each piece: register before launch finishes and only once, nil queue means a background queue, earliestBeginDate is a lower bound, and from iOS 27 submission moves to submitTaskRequest, behind #available while older releases are supported.
Show the failure modes you have seen: late registration on cold background launches, ignored submit errors, and handlers that forget to resubmit, and how you make each one visible.
Decide who owns identifiers in a growing app: one module that declares, registers and submits them, so features cannot register late or collide on the single refresh slot.
## Three things must line up A refresh in iOS's **Background Tasks** framework runs only when three pieces agree on one identifier string, for a podcast app say `com.example.podcasts.episode-refresh`: 1. **Info.plist declares it.** The identifier is listed in `BGTaskSchedulerPermittedIdentifiers`, and the matching value is in `UIBackgroundModes`: `fetch` for app refresh, `processing` for processing tasks. Xcode's Background Modes capability edits that second array. 2. **The app registers a launch handler for it** before launch finishes. 3. **The app submits a request with it**, and submits a new one after every run. Miss one and nothing fails at build time. The refresh simply never arrives, or submission reports an error the app never looks at. ## Declaring the identifier and the mode `BGTaskSchedulerPermittedIdentifiers` is an array of strings. The `BGTaskScheduler` header says every identifier in it requires a handler, and `register(forTaskWithIdentifier:using:launchHandler:)` returns `false` when the identifier is missing from the array. Submitting a request whose identifier is not listed, or whose task type's background mode is absent, fails with the `notPermitted` error code. | Piece | Where it lives | What breaks without it | |---|---|---| | Permitted identifier | `BGTaskSchedulerPermittedIdentifiers` in Info.plist | `register` returns `false`; submit fails with `notPermitted` | | Background mode | `fetch` or `processing` in `UIBackgroundModes` | Submit fails with `notPermitted` | | Launch handler | `register(...)` during launch | A background launch finds no handler to call | | Submitted request | `BGAppRefreshTaskRequest` passed to the scheduler | Nothing is scheduled, so nothing runs | | Resubmission | Inside the launch handler | The refresh runs once, then stops | ## Registering before launch ends Registration ties an identifier to a closure. The header's rules: - All launch handlers must be registered **before the app finishes launching**; in a UIKit app that means inside `application(_:didFinishLaunchingWithOptions:)`. A background launch for the refresh may start the app from scratch, and the handler must exist by the end of that launch. - **Register each identifier once.** Registering after launch, or a second handler for the same identifier, is an error, and the header says the system kills the app on the second registration of the same identifier. - The `using:` parameter takes a dispatch queue; **`nil` means a default background queue**, so the handler is not on the main thread unless you pass the main queue. - The handler receives a `BGTask`; cast it to `BGAppRefreshTask`, and still complete the task if the cast ever fails. Registering from a screen's view controller, or behind a feature flag that arrives from the network, is the classic way to make the refresh never run on a cold background launch. ## Submitting, and submitting again The app builds a `BGAppRefreshTaskRequest(identifier:)`, optionally sets `earliestBeginDate`, a "not before" date and never a schedule, and submits it. - The **iOS 27 SDK** adds `submitTaskRequest(_:completionHandler:)`, in Swift usually `try await BGTaskScheduler.shared.submitTaskRequest(request)`. It is **available from iOS 27** only. - The older throwing **`submit(_:)`**, available since iOS 13, is **deprecated from iOS 27**; the deprecation message says the replacement exists "to capture all error conditions". The warning appears once the deployment target is iOS 27 or later. - An app whose deployment target is older calls the new method inside `if #available(iOS 27, *)` and keeps `try submit(request)` in the `else` branch, as the example below does. - The header asks you not to call the new method from the main thread or from performance-critical code, and notes that its completion may arrive on an arbitrary queue after an arbitrary delay. A request is **one-shot**. When the launch handler runs, the request is spent, so the handler submits the next one, typically first, so that a failure later in the run does not leave nothing scheduled. Only one refresh request can be pending, and resubmitting the same identifier replaces the pending one, so rescheduling never piles up requests. ## The SwiftUI path A SwiftUI app can skip the explicit registration. SwiftUI's `backgroundTask(_:action:)` scene modifier, available since iOS 16, takes `.appRefresh(_:)` with the identifier and an async closure: ```swift @main struct PodcastApp: App { var body: some Scene { WindowGroup { LibraryView() } .backgroundTask(.appRefresh("com.example.podcasts.episode-refresh")) { await EpisodeFeed.refreshAndReschedule() // app-defined } } } ``` The closure receives no `BGTask`, so there is no `expirationHandler` to assign and no `setTaskCompleted(success:)` to call: SwiftUI manages the task around the closure. Everything else stays the app's job: the Info.plist identifier and `fetch` mode, submitting the `BGAppRefreshTaskRequest` in the first place, and submitting the next one from inside the closure. Give each identifier one owner, the modifier or an explicit registration, never both. ## What this does not cover How often iOS grants refresh launches and what a design may count on belongs to the mobile system design material on background limits. Background downloads that continue while the app is suspended belong to the URLSession lesson.
- With BGTaskScheduler, why submit the next refresh at the start of the launch handler rather than at the end?A request runs once. If the work throws or the task expires before the end, a submit placed there never happens and refreshes stop until the next foreground launch. Submitting first costs nothing, because resubmitting the same identifier replaces any pending refresh request.
- Can an app extension submit a BGTaskScheduler request, and which process is launched to run it?Some extensions can submit, but the header says only the host app is launched to handle the background work, so the launch handler lives in the app's launch path. Some extension types cannot schedule at all and get the `unavailable` error.
- With SwiftUI's .backgroundTask(.appRefresh(_:)) modifier, how does the app keep refreshes coming?SwiftUI provides the handler, not the schedule. The app still submits a `BGAppRefreshTaskRequest` through `BGTaskScheduler`: once, for example when the scene moves to the background, and again from inside the closure on every run.
- Register the launch handler the first time the episodes screen appears
- Listing the identifier in Info.plist is enough; no background mode is needed
- One submitted BGAppRefreshTaskRequest keeps repeating on its own
- Calling register again on every scene activation is harmless
- SwiftUI's backgroundTask modifier submits the refresh request for you
Assumes the iOS 27 SDK: submitTaskRequest(_:completionHandler:) and its async form need iOS 27 at runtime and deprecate the throwing submit(_:) from iOS 27, so a lower deployment target keeps submit(_:) behind #available; SwiftUI's backgroundTask scene modifier needs iOS 16.