M-Swift All articles
Testing & Tooling

The Silent Stall: Auditing BGTaskScheduler Before Users Notice Stale Data

M-Swift
The Silent Stall: Auditing BGTaskScheduler Before Users Notice Stale Data

Photo: Youcef Smahi, CC BY 4.0, via Wikimedia Commons

Every team has one of these stories. The feed refreshes on schedule during development, the TestFlight build looks fine, and then the App Store version sits there with Tuesday's headlines on Friday. Nobody changed anything. The refresh task just... stopped calling back.

That's not bad luck. Background refresh on iOS is a request, not a guarantee, and Apple treats it like a loan officer treats a first-time borrower: generous at first, stingy the moment you look unreliable. The audit below is how you find out which of those two you are.

Why Your Desk Setup Lies to You

A plugged-in iPhone with the app in the foreground and Xcode attached is the most forgiving environment iOS has. The system has no reason to throttle you, no thermal pressure, no low battery, no user who force-quit the app two days ago.

Production is the opposite. Users swipe apps away, enable Low Power Mode, turn off Background App Refresh in Settings, and let iOS offload rarely-used apps. On top of that, the scheduler gives you fewer opportunities the more you miss or the more time you burn. So the first rule of auditing background work is simple: never trust a result that came from the simulator, and be suspicious of any result from a device that's been sitting on your desk charging.

Registration Is a Contract, Not a Checkbox

The most common failure I see is registration that happens too late. BGTaskScheduler.register has to run before application(_:didFinishLaunchingWithOptions:) returns, and before the app finishes launching in a scene-based lifecycle too. If you moved it into a view model or a lazy singleton that initializes when the home screen appears, the system may already have tried to launch your task and given up.

Second: every identifier needs a matching entry in BGTaskSchedulerPermittedIdentifiers in Info.plist. A typo there doesn't crash. It just returns false from register, and if you never check that return value, you've shipped an app that quietly never reschedules.

private func registerBackgroundTasks() {
    let refresh = BGAppRefreshTaskRequest(identifier: FeedRefresh.identifier)
    refresh.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)

    do {
        try BGTaskScheduler.shared.submit(refresh)
    } catch {
        Logger.background.error("submit failed: \(error.localizedDescription, privacy: .public)")
    }
}

Three things to check here. Is the submit call wrapped in a do/catch? Is the identifier a single source of truth shared between the task request and the Info.plist? And is the registration actually happening in the launch path you think it is?

Expiration Handlers: The Part Everyone Skips

iOS gives background tasks a short window, often well under a minute. When that window closes, your expiration handler fires, and you have a very small amount of time to stop cleanly. Teams frequently set a handler that does nothing, or one that cancels work but never calls setTaskCompleted.

That second mistake is the expensive one. If the system asks you to wrap up and you don't confirm, it counts against you. Repeat it a few times and the scheduler gets stingy. Here's the pattern that holds up:

func handleRefresh(_ task: BGAppRefreshTask) {
    scheduleNextRefresh() // reschedule first, always

    let work = Task { await feedService.refresh() }

    task.expirationHandler = {
        work.cancel()
        task.setTaskCompleted(success: false)
    }

    Task {
        let ok = await work.value
        task.setTaskCompleted(success: ok)
    }
}

The reschedule call goes first, not last. If your process gets killed mid-refresh, you still want the next opportunity queued. This is the single highest-leverage change in most codebases I've looked at.

The Budget Conversation Nobody Has

Background refresh doesn't run on a timer. It runs when iOS decides you've earned it, based on how often the user opens your app, whether they interact with notifications, battery state, and how well you've behaved historically. An app opened five times a day gets treated very differently from one opened twice a week.

That means your earliestBeginDate is a suggestion, not a schedule. If you set it to five minutes and treat twenty minutes as a failure, you'll spend a sprint chasing a bug that doesn't exist. What you should be measuring instead is whether the task runs at all over a 48-hour window on a device that's been in someone's pocket, and how often your expiration handler fires without a clean completion.

Two signals worth logging with os.Logger under a dedicated subsystem: every successful submit, and every task completion with its success flag. Pipe those to Console.app during a device run and you'll see the pattern in an afternoon.

A Real-Device Audit You Can Run This Week

Here's the loop I use. It takes about a day per build and catches the failures that matter.

Install the build on a physical device, launch it once, then leave it alone. Don't tap anything. Come back in two hours, then six, then overnight. Watch the log stream from Console.app filtered to your subsystem, and check the order of events. You want to see submit, launch, completion, resubmit. Anything that breaks that chain is your bug.

Next, run the hostile scenarios deliberately. Kill the app with the app switcher and confirm that background tasks don't resume until the user relaunches. That's expected behavior, but your UI shouldn't imply otherwise. Enable Low Power Mode and check that you degrade gracefully rather than showing a spinner forever. Then open Settings, turn off Background App Refresh for your app, and make sure the in-app experience still tells a coherent story about how fresh the data is.

Finally, check your database. A refresh task that runs and writes nothing is indistinguishable from one that never ran, if you're only looking at the UI. Log a lightweight row count or a last-updated timestamp on every successful pass, and surface that timestamp somewhere a support engineer can find it. Give the whole audit a couple of cold-start passes on a clean install, too, since the scheduling history resets.

Make the Silent Failure Loud

The frustrating thing about background refresh is how quiet it is when it breaks. No crash, no symbolicated report, just content that quietly ages out while the user assumes you've abandoned the app. Treat the scheduler like any other external dependency: log the boundary, verify the contract on real hardware, and build one hostile-state test for every assumption you're making about when the system will call you back.

The loan will be extended as long as you keep paying on time. Auditing is how you make sure you actually are.

All Articles

Related Articles

Crash Logs Don't Fix Themselves: A Weekly MetricKit Triage the Whole Team Can Stomach

Crash Logs Don't Fix Themselves: A Weekly MetricKit Triage the Whole Team Can Stomach

Dress Rehearsal for SwiftData: Testing Schema Changes on Copies of Real User Stores

Dress Rehearsal for SwiftData: Testing Schema Changes on Copies of Real User Stores

Paper Trail, Not Bug Hunt: Preflighting Privacy Manifests in Swift Dependencies

Paper Trail, Not Bug Hunt: Preflighting Privacy Manifests in Swift Dependencies