Est.

Guide · iOS Performance

iOS Background Tasks: Choosing, Scheduling and Debugging Them

Which iOS background API fits the work, how to set up BGTaskScheduler for app refresh and processing tasks, and why a scheduled background task never runs.

Updated

In short

  • iOS has no single background task API. Finishing a save the user started is `beginBackgroundTask`; refreshing content is `BGAppRefreshTask`; heavy, deferrable work is `BGProcessingTask`; a long job the user starts and watches is `BGContinuedProcessingTask` (iOS 26); large transfers belong to a background `URLSession`.
  • Scheduled tasks need three things before they ever run: the right Background Modes capability, the identifier in `BGTaskSchedulerPermittedIdentifiers`, and a launch handler registered before the app finishes launching.
  • The system, not your app, decides when a scheduled task runs. `earliestBeginDate` is a floor, not a time; the Simulator, Background App Refresh being off, Low Power Mode and quitting the app from the app switcher can all mean it doesn't run at all.

Which background API fits the work

When an app leaves the foreground, iOS suspends it shortly afterwards. Every way of running code after that is a request the system can grant, delay or cut short, and each one is meant for a different kind of work. Pick by what the work is, not by how long you'd like it to run:

The workAPIWhat the system gives you
Finishing something the user started: saving a file, sending a messageUIApplication.beginBackgroundTask(withName:expirationHandler:) and endBackgroundTask(_:)A limited amount of extra time after the app moves to the background. Read backgroundTimeRemaining for the maximum; don't plan around a fixed number.
Refreshing content regularly: the latest prices, a feed, a small syncBGAppRefreshTask, requested with BGAppRefreshTaskRequestUp to 30 seconds of runtime, at a time the system chooses.
Heavy work that can wait: database maintenance, indexing, training a model, a large syncBGProcessingTask, requested with BGProcessingTaskRequestCan run for minutes, but only while the device is idle; the system ends it when the user starts using the device.
A long job the user starts and expects to finish: exporting a video, processing a batch of photosBGContinuedProcessingTask (iOS 26 and later)Starts in the foreground and keeps running in the background, with its progress shown in a Live Activity where the user can cancel it.
Downloading or uploading filesA background URLSessionThe transfer runs in a separate system process, even while the app is suspended or after it's terminated.
Reacting when your server has something newA background push (content-available: 1)Up to 30 seconds once delivered. Apple rate-limits background pushes sent more than three times an hour.

Two of these get confused most often. beginBackgroundTask doesn't schedule anything: it only asks for time to finish work already under way. And a BGAppRefreshTask isn't a timer: you can say when it may start, never when it will. Agent-style work that has to keep going after the user leaves the app has its own constraints, covered in Background Agent Tasks on iOS Within App Lifecycle Constraints.

Setting up BGTaskScheduler

App refresh and processing tasks go through BGTaskScheduler in the BackgroundTasks framework (iOS 13 and later). Every one of these steps is required; skip one and the task either fails to register or never launches:

  1. Add the capability. In the target's Signing & Capabilities tab, add Background Modes, then tick "Background fetch" for BGAppRefreshTask and "Background processing" for BGProcessingTask.
  2. List the identifiers. Add "Permitted background task scheduler identifiers" (BGTaskSchedulerPermittedIdentifiers) to the Info.plist, with one string per task in reverse-DNS form, such as com.example.app.refresh.
  3. Register a launch handler for every listed identifier with BGTaskScheduler.shared.register(forTaskWithIdentifier:using:launchHandler:), and finish registering before the app's launch sequence ends. Register each identifier once only: the system kills the app on a second registration of the same identifier.
  4. Submit a request with BGTaskScheduler.shared.submit(_:) when you want the work to happen. Submitting again for the same identifier replaces the earlier request.
  5. In the handler, set the task's expirationHandler, do the work, and call setTaskCompleted(success:) when it's done.

register returns false if the identifier isn't in BGTaskSchedulerPermittedIdentifiers, so check it rather than ignoring it. An app extension can submit a request, but the main app has to register the handler, because the system launches the app to run the task. Adding BGTaskSchedulerPermittedIdentifiers also turns off the older application(_:performFetchWithCompletionHandler:) and setMinimumBackgroundFetchInterval(_:), so move any background fetch code over at the same time.

App refresh tasks

A refresh task is for small, quick updates. Schedule the next refresh as soon as one starts, so the chain doesn't stop, and make the expiration handler cancel the work so the task always completes:

import BackgroundTasks

let refreshID = "com.example.app.refresh"   // also listed in Info.plist

// Call from application(_:didFinishLaunchingWithOptions:), before it returns.
func registerBackgroundTasks() {
    BGTaskScheduler.shared.register(forTaskWithIdentifier: refreshID, using: nil) { task in
        handleAppRefresh(task as! BGAppRefreshTask)
    }
}

func scheduleAppRefresh() {
    let request = BGAppRefreshTaskRequest(identifier: refreshID)
    request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)   // no earlier than 15 min
    do {
        try BGTaskScheduler.shared.submit(request)
    } catch {
        // .unavailable on Simulator, or when Background App Refresh is off
        print("Couldn't schedule app refresh: \(error)")
    }
}

func handleAppRefresh(_ task: BGAppRefreshTask) {
    scheduleAppRefresh()   // ask for the next one first

    let work = Task {
        do {
            try await refreshContent()   // your code; should honour cancellation
            task.setTaskCompleted(success: true)
        } catch {
            task.setTaskCompleted(success: false)
        }
    }
    task.expirationHandler = { work.cancel() }
}

Apple gives a refresh task up to 30 seconds and terminates the app if it doesn't call setTaskCompleted(success:) within that time. Keep the work small: fetch only what changed, and leave anything heavy for a processing task. URLSession and Network Efficiency in High-Frequency iOS Apps covers keeping requests like these cheap.

In a SwiftUI app you can skip the delegate code and attach the handler to the scene with .backgroundTask(.appRefresh("com.example.app.refresh")) { await refreshContent() } (iOS 16 and later). The system treats the task as complete when the closure returns, and cancels it if it runs out of time, so the work inside has to respond to Swift task cancellation. You still add the capability and the Info.plist identifier, and still submit the BGAppRefreshTaskRequest yourself.

Processing tasks

A processing task is for work that's too long for a refresh and can wait for a good moment. You can tell the system what the work needs, and it will hold the task until those conditions are met:

let request = BGProcessingTaskRequest(identifier: "com.example.app.db-maintenance")
request.requiresExternalPower = true          // wait until the device is charging
request.requiresNetworkConnectivity = false   // this job is local only
try BGTaskScheduler.shared.submit(request)
  • Processing tasks run only while the device is idle, and the system ends them when the user starts using the device. Set an expirationHandler that stops cleanly and saves how far the work got.
  • Make the work resumable. Split it into batches, commit after each one, and let the next run start from where the last one stopped.
  • Asking for external power makes the task far less likely to cost the user battery, and is a good default for anything that isn't urgent. Battery Impact Profiling with Energy Log and MetricKit shows how to measure what background work costs.

Continued processing tasks (iOS 26)

BGContinuedProcessingTask covers a case the older types didn't: a job the user starts, such as an export, that should keep going if they switch to another app. Unlike other task types, it starts in the foreground, and it must be submitted in response to something the user did, such as tapping a button.

let exportID = "com.example.app.export"   // prefixed with your bundle ID

let request = BGContinuedProcessingTaskRequest(
    identifier: exportID,
    title: "Exporting video",
    subtitle: "About to start…"
)
request.strategy = .fail   // fail now rather than queue if it can't start immediately
try BGTaskScheduler.shared.submit(request)
  • The system shows the task's title, subtitle and progress in a Live Activity, and the user can cancel it there. Cancelling calls the task's expiration handler.
  • Report progress through the task's progress (it conforms to ProgressReporting). Under resource pressure the system ends tasks that show little or no progress first, and a task that looks stuck invites the user to cancel it.
  • The default strategy is .queue, which waits for room to run. .fail cancels the request straight away if it can't begin now.
  • For GPU work in the background, check that BGTaskScheduler.supportedResources contains .gpu, set requiredResources = .gpu, and add the Background GPU Access capability.
  • Closing the app in the app switcher cancels running tasks, and the app isn't told. Save progress as you go.

Finishing work as the app goes to the background

applicationDidEnterBackground(_:) has five seconds to return, and the app is suspended shortly after. For anything that may take longer, such as writing a file or sending a request the user is waiting on, call beginBackgroundTask(withName:expirationHandler:) before you start the work, not once the app is already on its way to the background.

  • Keep the identifier it returns and pass it to endBackgroundTask(_:) as soon as the work finishes. Every begin needs a matching end; if a task isn't ended before time runs out, the system kills the app.
  • In the expiration handler, stop the work and end the task. The system also calls it if it can't grant the extra time at all.
  • The call returns .invalid when running in the background isn't possible, so handle that case.
  • App extensions can't use it; they call ProcessInfo.performExpiringActivity(withReason:using:) instead.

If the work is a download or an upload, use a background URLSession instead of holding the app awake: the transfer carries on in a system process, and the system relaunches the app through application(_:handleEventsForBackgroundURLSession:completionHandler:) when it finishes. Use one session for many transfers rather than starting them one at a time, because the system adds a growing delay each time it resumes the app to start another.

Why a background task doesn't run

SymptomLikely causeWhat to do
submit(_:) throws BGTaskScheduler.Error.Code.unavailableRunning on the Simulator, which doesn't support background processing, or the user turned off Background App RefreshTest on a device. At runtime, check UIApplication.shared.backgroundRefreshStatus and design for .denied and .restricted.
register returns falseThe identifier isn't in BGTaskSchedulerPermittedIdentifiers, or doesn't match exactlyCopy the identifier from one constant into both places.
The handler is never calledRegistration happens after launch finishes, for example in a view's onAppear, or the Background Modes capability is missingRegister in application(_:didFinishLaunchingWithOptions:) (or the app's initializer) and check the capability for each task type.
The app is killed at launchThe same identifier is registered twiceRegister once, at launch, from a single place.
It runs hours later than earliestBeginDateExpected: the date only guarantees the task won't start soonerDon't build features that depend on a background refresh at a set time. Refresh when the app comes to the foreground too.
It stopped running for one userLow Power Mode turns off Background App Refresh, and an app quit from the app switcher might not run until it's opened againNothing to fix in code. Treat background refresh as a bonus and make sure the foreground path still works on its own.
A processing task keeps getting cut shortThe user started using the device, or the system needed the resourcesHandle expiration, save progress in batches, and consider requiresExternalPower.
Only the latest request seems to countA new submit(_:) for the same identifier replaces the previous oneUse separate identifiers for jobs that should be scheduled independently.

A background-launched app is still held to the system's memory limits, and suspended apps with a large footprint are the first to go when memory runs low; Jetsam Events on iOS covers reading those terminations.

Testing background tasks during development

The wait between submitting a task and the system running it can be many hours, so Apple provides two debugger commands that launch or expire a task on demand. They work only on a device, not in the Simulator. Set a breakpoint just after a successful submit(_:), run the app until it pauses, then enter:

e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.example.app.refresh"]

Resume, and the system calls the launch handler. To test the expiration path, pause at a breakpoint inside the running task and enter:

e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@"com.example.app.refresh"]

These call private methods. Use them only from the debugger: an app that references them in its code is rejected from the App Store.

Watching background work in the field

Background work that misbehaves shows up as terminations and battery drain users never report. MetricKit's app exit metrics count background exits by cause; before iOS 27, MXAppExitMetric's background exit data includes cumulativeBackgroundTaskAssertionTimeoutExitCount, the number of times the app was killed for not ending a beginBackgroundTask in time. Check Apple's MetricKit documentation for the types available on the OS versions you support. Instruments and MetricKit for iOS App Monitoring covers collecting these reports, and Thermal State Management and Adaptive Performance Throttling in iOS covers scaling heavy work back when the device is hot.

Sources