skip to content

A podcast app's BGTaskScheduler episode refresh never seems to run during testing; how do you diagnose it, and how do you force a launch and an expiration from the debugger?

level: seniorimportance: should knowfreq 35%

answer

  1. not yet is not never
  2. read the Bool and the error
  3. Simulator versus a real device
  4. private simulate calls in LLDB

basics

~10 s

Check that register returns true during launch and that submission succeeds, reading the BGTaskScheduler.Error code, on a real device. Then, paused in LLDB after a successful submit, call the private _simulateLaunchForTaskWithIdentifier: and _simulateExpirationForTaskWithIdentifier: methods.

solid answer

~50 s

First separate "not yet" from "never": Apple's development guide says the gap between scheduling and launch can be many hours. Then prove each link. `register(forTaskWithIdentifier:using:launchHandler:)` must return `true` before launch finishes. The submission must succeed, and a caught `BGTaskScheduler.Error` code tells you why it didn't, from `submitTaskRequest(_:)` on iOS 27 or the throwing `submit(_:)` before it. `unavailable` points to the Simulator, Background App Refresh switched off, or an extension that can't schedule. `notPermitted` usually means a missing background mode or a missing `BGTaskSchedulerPermittedIdentifiers` entry. `tooManyPendingTaskRequests` means the app tried to exceed one pending refresh or ten pending processing requests. `getPendingTaskRequests(completionHandler:)` shows what is queued. To test without waiting, run on a device, pause after a successful submit, and in LLDB call `_simulateLaunchForTaskWithIdentifier:`, then `_simulateExpirationForTaskWithIdentifier:` to drive the expiration handler. They are private: never ship a reference to them.

code

swift · 26 lines
swift
import BackgroundTasks

nonisolated func submitAndExplain(_ request: BGTaskRequest) async {
    do {
        if #available(iOS 27, *) {
            try await BGTaskScheduler.shared.submitTaskRequest(request)
        } else {
            try BGTaskScheduler.shared.submit(request)
        }
    } catch let error as BGTaskScheduler.Error {
        switch error.code {
        case .unavailable:
            print("Unavailable: Simulator, Background App Refresh off, or an extension that can't schedule")
        case .notPermitted:
            print("Not permitted: check UIBackgroundModes and BGTaskSchedulerPermittedIdentifiers")
        case .tooManyPendingTaskRequests:
            print("Too many pending: 1 refresh and 10 processing requests at most")
        case .immediateRunIneligible:
            print("Continued processing with the .fail strategy could not start now")
        @unknown default:
            print("Unknown scheduler error: \(error)")
        }
    } catch {
        print("Submit failed: \(error)")
    }
}

go deeper

for a junior

Recall that background tasks need a real device to test, and that the system can wait hours before running one.

for a middle

Explain the checks in order: register's return value and timing, the submission error code, the pending requests and the person's background refresh setting.

for a senior

Show you can drive both paths on a device from LLDB, launch then expiration, and that you map each BGTaskScheduler.Error code to the Info.plist, setting or limit behind it.

for a principal

Make background work observable in production: log every submit outcome and every launch, completion and expiry, so 'it never runs' arrives with data rather than guesses.

## First, separate "not yet" from "never" A refresh in iOS's **Background Tasks** framework runs when the system decides, not when the developer watches. Apple's guide to starting and terminating tasks during development says the delay between scheduling a task and the launch "can be many hours", and `earliestBeginDate` is only a lower bound. So "it didn't run in the last hour" proves nothing. Diagnosis means proving each link in code, then forcing the launch from the debugger so the handler can be tested on demand. ## Check every link in code 1. **The registration result.** `register(forTaskWithIdentifier:using:launchHandler:)` returns a Bool. `false` means the identifier is missing from `BGTaskSchedulerPermittedIdentifiers` in Info.plist; assert on it in debug builds. 2. **The registration timing.** Handlers must be registered before the app finishes launching, once per identifier. A handler registered from a screen runs fine while the app is open and is absent on a cold background launch. 3. **The submission result.** Failures arrive as a `BGTaskScheduler.Error`. Code that wrapped the throwing `submit(_:)` in `try?` never saw why it failed. On iOS 27 and later, `submitTaskRequest(_:)` replaces it, and the header says the replacement exists to capture all error conditions; it is unavailable before iOS 27, so an app supporting older releases calls it inside `if #available(iOS 27, *)` and keeps `submit(_:)` for the rest. 4. **What is pending.** `getPendingTaskRequests(completionHandler:)` returns copies of submitted, not yet completed requests. An empty list means the request was never submitted, or it already ran and the handler did not submit a new one. 5. **The user's setting.** UIKit's `backgroundRefreshStatus` on `UIApplication` reports whether the app can refresh in the background; a person can switch Background App Refresh off. 6. **The resubmission.** If the refresh ran once and then never again, the launch handler is not submitting the next request. Requests are one-shot, so every run must submit its successor, ideally before doing the work. 7. **The completion.** A handler that never calls `setTaskCompleted(success:)`, or never assigns an `expirationHandler`, makes each run end badly, which is worth ruling out before blaming the schedule. ## Reading the error codes The `BGTaskScheduler` header documents four codes, with these causes: | Code | Causes the header lists | Typical fix | |---|---|---| | `unavailable` | Background refresh disabled in Settings; running in Simulator; a keyboard extension without open access; an extension type that can't schedule | Test on a device; degrade gracefully when the person has switched refresh off | | `notPermitted` | Missing mode in `UIBackgroundModes`; identifier not in `BGTaskSchedulerPermittedIdentifiers`; unavailable continued-processing resources; the person denied background launches | Fix Info.plist or the capability | | `tooManyPendingTaskRequests` | More than 1 refresh or 10 processing requests pending | Reuse one identifier per job; cancel stale requests with `cancel(taskRequestWithIdentifier:)` | | `immediateRunIneligible` | A continued-processing request with the `.fail` strategy could not start right away | Only applies to continued processing | Two of these surprise people. The Simulator does not support background processing, so a Simulator-only test run can never pass. And two refresh identifiers cannot both be pending, because the scheduler allows one refresh request in total. ## Forcing a launch from the debugger Apple documents two private `BGTaskScheduler` methods for development. They work **only on devices**. To launch a task: - Set a breakpoint in code that runs after a successful submit, and run the app on a device until it pauses there. - In LLDB, evaluate an Objective-C expression that sends `_simulateLaunchForTaskWithIdentifier:` to `[BGTaskScheduler sharedScheduler]` with your identifier. - Resume the app. The system calls the launch handler registered for that identifier. ## Forcing an expiration - Set a breakpoint inside the task's work. - Launch the task with the command above and wait for the app to pause at that breakpoint. - Evaluate `_simulateExpirationForTaskWithIdentifier:` the same way, then resume. The system calls the task's `expirationHandler`. Now the stop path can be watched: the work should see cancellation, return, and call `setTaskCompleted(success:)` once. ## Keep the private calls out of the app The guide is explicit: use these functions only during development, and an app submitted to the App Store that references them is cause for rejection. Type them in the debugger; never put them in Swift source, not even behind a debug flag that could ship. What the debugger proves is that the handler works when launched and stops cleanly when expired. It does not show how often a real device will grant launches; that question belongs to the mobile system design material on background limits.

  • Why does a BGTaskScheduler refresh that works when launched from LLDB still not run on a tester's phone?
    The command proves the handler, not the schedule. The system picks the launch time from conditions and usage, so a refresh can wait many hours, and a person may have switched Background App Refresh off. Check `backgroundRefreshStatus` and the pending requests before blaming the code.
  • Which BGTaskScheduler error separates 'the person switched Background App Refresh off' from 'the person denied background launches for this app'?
    The header lists the Settings switch for background refresh under `unavailable`, and an explicit denial of background launches for the app under `notPermitted`. `notPermitted` far more often means a missing background mode or identifier, so check Info.plist first.

  • Testing BGTaskScheduler in the Simulator works; the task just takes longer
  • If submission doesn't fail, the task will run soon after earliestBeginDate
  • Wrapping submit in try? is fine because errors are rare
  • The simulate-launch call can stay in the app behind a debug flag
  • notPermitted always means the person switched something off in Settings

Assumes the iOS 27 SDK: submitTaskRequest(_:completionHandler:), available from iOS 27, replaces the throwing submit(_:), deprecated from iOS 27, so every BGTaskScheduler.Error reaches the caller; older releases keep submit(_:).