General:
Forums subtopic: App & System Services > Processes & Concurrency
Forums tag: Background Tasks
Background Tasks framework documentation
UIApplication background tasks documentation
ProcessInfo expiring activity documentation
Using background tasks documentation for watchOS
Performing long-running tasks on iOS and iPadOS documentation
WWDC 2020 Session 10063 Background execution demystified — This is critical resource. Watch it! [1]
WWDC 2022 Session 10142 Efficiency awaits: Background tasks in SwiftUI
iOS Background Execution Limits forums post
UIApplication Background Task Notes forums post
Testing and Debugging Code Running in the Background forums post
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] Sadly the video is currently not available from Apple. I’ve left the link in place just in case it comes back.
Background Tasks
RSS for tagRequest the system to launch your app in the background to run tasks using Background Tasks.
Posts under Background Tasks tag
151 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hello,
My watchOS app has been performing fine by requesting background app refresh and then requesting any new data from health kit in the background so that the widget can be updated. However, on watchos26 I have been unable to read data in the background, with any query returning zero results. That same data is clearly read just fine while in the foreground. Can anyone assist?
Issue:
I am making an application that stores data locally from notifications fired from the server. Everything works fine in the foreground but the background is having problems with not being triggered when notifications are fired.
So we tried firing 2 notifications at the same time, including default and silent types. But the problem continues to arise on ios 18, when firing multiple times like that, the trigger is not handling all notifications, leading to data loss. I tried on ios 15 and it worked fine.
Environment:
Device or Simulator: Iphone 11 pro max (iOS 18.3.2
Steps to Reproduce:
Open app, allow received notification.
Move app to background mode or terminate app.
Sent 2 notifications:
a. Default notification payload:
{
"aps": {
"content-available": 1
},
”notification”: {…},
“alert”: {..},
“data": "some_value"
}
b. Silent notification payload:
{
"aps": {
"content-available": 1
},
”data": "some_value"
}
What I've Tried:
Trigger notification in function:
application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
Handle write data to local storage in above function, put it in background thread also.
Thanks in advance!
Topic:
App & System Services
SubTopic:
Notifications
Tags:
APNS
Cloud and Local Storage
Background Tasks
I'm trying to understand how the API works to perform a function that can continue running if the user closes the app. For a very simple example, consider a function that increments a number on screen every second, counting from 1 to 100, reaching completion at 100. The user can stay in the app for 100s watching it work to completion, or the user can close the app say after 2s and do other things while watching it work to completion in the Live Activity.
To do this when the user taps a Start Counting button, you'd
1 Call BGTaskScheduler.shared.register(forTaskWithIdentifier:using:launchHandler:).
Question 1: Do I understand correctly, all of the logic to perform this counting operation would exist entirely in the launchHandler block (noting you could call another function you define passing it the task to be able to update its progress)? I am confused because the documentation states "The system runs the block of code for the launch handler when it launches the app in the background." but the app is already open in the foreground. This made me think this block is not going to be invoked until the user closes the app to inform you it's okay to continue processing in the background, but how would you know where to pick up. I want to confirm my thinking was wrong, that all the logic should be in this block from start to completion of the operation, and it's fine even if the app stays in the foreground the whole time.
2 Then you'd create a BGContinuedProcessingTaskRequest and set request.strategy = .fail for this example because you need it to start immediately per the user's explicit tap on the Start Counting button.
3 Call BGTaskScheduler.shared.submit(request).
Question 2: If the submit function throws an error, should you handle it by just performing the counting operation logic (call your function without passing a task)? I understand this can happen if for some reason the system couldn't immediately run it, like if there's already too many pending task requests. Seems you should not show an error message to the user, should still perform the request and just not support background continued processing for it (and perhaps consider showing a light warning "this operation can't be continued in the background so keep the app open"). Or should you still queue it up even though the user wants to start counting now? That leads to my next question
Question 3: In what scenario would you not want the operation to start immediately (the queue behavior which is the default), given the app is already in the foreground and the user requested some operation? I'm struggling to think of an example, like a button titled Compress Photos Whenever You Can, and it may start immediately or maybe it won't? While waiting for the launchHandler to be invoked, should the UI just show 0% progress or "Pending" until the system can get to this task in the queue? Struggling to understand the use cases here, why make the user wait to start processing when they might not even intend to close the app during the operation?
Thanks for any insights! As an aside, a sample project with a couple use cases would have been incredibly helpful to understand how the API is expected to be used.
Hello,
An application I am working on would like to schedule push notifications for a medication reminder app. I am trying to use BGTaskScheduler to wake up periodically and submit the notifications based on the user's medication schedule.
I set up the task registration in my AppDelegate's didFinishLaunchingWithOptions method:
BGTaskScheduler.shared.register(
forTaskWithIdentifier: backgroundTaskIdentifier,
using: nil) { task in
self.scheduleNotifications()
task.setTaskCompleted(success: true)
self.scheduleAppRefresh()
}
scheduleAppRefresh()
I then schedule the task using:
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: backgroundTaskIdentifier)
request.earliestBeginDate = Date(timeIntervalSinceNow: 60 * 1)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
}
}
In my testing, I can see the background task getting called once, but if I do not launch the application during the day. The background task does not get called the next day.
Is there something else I need to add to get repeated calls from the BGTaskScheduler?
Thank You,
JR
Topic:
App & System Services
SubTopic:
Processes & Concurrency
Tags:
Background Tasks
User Notifications
Hello, appreciate any help here.
Objective: perform a scoped write to a removable block device (using low-level system frameworks in C).
Issue: launchd-run privileged helper (as root) denied permission to open block device. Manual 'sudo ./helper' call succeeds, however.
Importantly: the entire process works flawlessly if the main app is granted Full Disk Access in Privacy & Security. However, this should be completely unnecessary for this objective, as scoped access should be sufficient, and FDA is in fact not required for other apps which perform this task.
Architecture and flow:
Main GUI process collects ISO path and target removable device path (queried via IOKit).
Main GUI process installs a Privileged Helper via SMJobBless.
The Privileged Helper is started on demand by launchd as root (UID 0, EUID 0).
Main GUI process communicates selected ISO and device paths to Privileged Helper via XPC.
Privileged Helper conducts security and sanity checks, unmounts volumes from target device via DiskArbitration.
Privileged Helper obtains file handles to ISO and target block device (e.g.: "/dev/disk4").
Privileged Helper performs a byte-by-byte write to the target block device.
Problematic area:
Simplified example using C syscalls (via Zig):
const path = "/dev/disk5";
// Note that even with readonly flag this fails
const fd = c.open(path, c.O_RDONLY, @as(c_uint, 0));
defer _ = c.close(fd);
if (fd < 0) {
const err_num = c.__error().*;
const err_str = c.strerror(err_num);
log("open() failed with errno {}: {s}", .{ err_num, err_str });
}
Output (when run by launchd - UID 0, EUID 0, domain: system):
open() failed with errno 1: Operation not permitted
Simplified example with Zig open interface:
const directory = try std.fs.openDirAbsolute(deviceDir, .{ .no_follow = true });
const device = try directory.openFile("/dev/disk5", .{ .mode = .read_write, .lock = .exclusive });
errdefer device.close();
Output (when run by launchd - UID 0, EUID 0, domain: system):
Error: error.AccessDenied
Running the same examples by manually launching the binary with a test argument succeeds:
sudo ./helper "/dev/disk5"
...
Notable points:
Both Main GUI process and the Privileged Helper binary are codesigned (via codesign ...).
Privileged Helper has both Info.plist and Launchd.plist symbols exported into its binary.
Privileged Helper has no codesign flags (e.g.: for hardened runtime or others): CodeDirectory v=20400 size=8130 flags=0x0(none) hashes=248+2 location=embedded
Output of sudo launchctl print system/<helper-bundle-id> shows nothing of interest to indicate any security restrictions.
Appreciate any advice here!
Topic:
App & System Services
SubTopic:
Core OS
Tags:
Background Tasks
Disk Arbitration
Files and Storage
Recently, I've noticed that background Bluetooth scanning stops when I move an app to the background on an iPhone 17 device with Bluetooth 6. I'm curious about a solution. Background Bluetooth scanning doesn't stop on devices older than iOS 26, or on devices that were updated from an iPhone 17 or earlier to iOS 26.
I created my app. One of its functionality is receive remote notification in the background (it receives it from Firebase Cloud Messaging via APNS) and replies with device location data. This is "boat tracking and alarm" type of app.
It worked well both on my iPhone (where I use the same Apple ID as on developer's account) and on my son's iPad (different Apple ID). After the first review, when app was rejected with some remarks, background remote notifications completely stopped working on my iPhone. It looks like my iPhone put the app in permanent sleep. It never receives the background notifications. It receives them though in 2 case:
when I open the app (it is no longer in background)
when location is changed (it wakes app in the background). But the app should also respond when the device is stable at the position (I use both: precise and Significant Location Change. In the latter case changes are very rare). Btw, I scheduled a background task, not location, and it also never gets executed, so this workaround does not work.
I describe it, so any Apple engineer does not get confused, verifying that these remote notifications reach the device. NO, they never get through when app is in the background (THIS IS THE PROBLEM), not that they are never delivered (the are, in the foreground). And the proof that it is not a problem with the app or remote notification construction is:
they work on another drives (iPad) with no issues. Sometimes they are very delayed, sometimes almost instant. But usually they work.
they worked the same way on my iPhone (with my developer's Apple ID) before the first rejection, and I haven't messed with messaging functionality since then.
Now I am over with the last hope I had. I finally got my app release in App Store. I hoped official version would release some blockade my iOS put on my app. But unfortunately not. Official version works the same way as the test one. It works fine (receiving notifications in the background) on my son's iPad and it does not receive any background notification on my iPhone (100% block rate).
Can anyone help me how can I reset my apps limits, the iOS created for my app? It seems that the rejection was a sparkle here - this is just a hint. I can provide any system logs for Apple engineers from both devices (iPhone and iPad) if you would like to check this case.
Our app scans Bluetooth in the background.
However, the iPhone 17 device does not scan in the background.
ios 26
Is there anything I need to do?
Our app scans Bluetooth in the background.
However, the iPhone 17 device does not scan in the background.
ios 26
Is there anything I need to do?
The setting values are as follows.
device
connection interval min : 60
connection interval max : 75
slave latency : 0
supervision timeout : 4000
advertising interval : 20
Our app scans Bluetooth in the background.
However, the iPhone 17 device does not scan in the background.
ios 26
Is there anything I need to do?
device1
connection interval min : 60
connection interval max : 75
slave latency : 0
supervision timeout : 4000
advertising interval : 20
After iOS 26 was released to the public and our build began rollout, we started seeing a strange crash affect users immediately after the app goes to the background. According to the symbolication provided in Xcode, this appears to be the result of a UICollectionView potentially related to the keyboard and a UIAlertController. I’m not sure how an error somewhere else can cause a crash in our app which does not use UIKit in the background.
The feedback associated with this post is: FB20305833.
I will attach a sample of the crash report in my next comment.
The following code worked as expected on iOS 26 RC, but it no longer works on the official release of iOS 26.
Is there something I need to change in order to make it work on the official version?
Registration
BGTaskScheduler.shared.register(
forTaskWithIdentifier: taskIdentifier,
using: nil
) { task in
//////////////////////////////////////////////////////////////////////
// This closure is not called on the official release of iOS 26
//////////////////////////////////////////////////////////////////////
let task = task as! BGContinuedProcessingTask
var shouldContinue = true
task.expirationHandler = {
shouldContinue = false
}
task.progress.totalUnitCount = 100
task.progress.completedUnitCount = 0
while shouldContinue {
sleep(1)
task.progress.completedUnitCount += 1
task.updateTitle("\(task.progress.completedUnitCount) / \(task.progress.totalUnitCount)", subtitle: "any subtitle")
if task.progress.completedUnitCount == task.progress.totalUnitCount {
break
}
}
let completed = task.progress.completedUnitCount >= task.progress.totalUnitCount
if completed {
task.updateTitle("Completed", subtitle: "")
}
task.setTaskCompleted(success: completed)
}
Request
let request = BGContinuedProcessingTaskRequest(
identifier: taskIdentifier,
title: "any title",
subtitle: "any subtitle",
)
request.strategy = .queue
try BGTaskScheduler.shared.submit(request)
Sample project code:
https://github.com/HikaruSato/ExampleBackgroundProcess
In iOS Background Execution limits, I see this:
When the user ‘force quits’ an app by swiping up in the multitasking UI, iOS interprets that to mean that the user doesn’t want the app running at all. iOS also sets a flag that prevents the app from being launched in the background. That flag gets cleared when the user next launches the app manually.
However, I see that when I close an app on iPadOS 26 with the red X, the app doesn't appear in the multitasking UI. So are they treated as force closes and prevented from running background tasks?
Our VoIP app receives PushKit notifications successfully (callservicesd Delivering 1 VoIP payload appears in logs). However, the app is consistently terminated by the system when running in the background or killed state.
The crash is caused by iOS expecting a reportNewIncomingCall to CallKit, but the system reports:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'Killing app because it never posted an incoming call to the system after receiving a PushKit VoIP push.'
*** Assertion failure in -[PKPushRegistry _terminateAppIfThereAreUnhandledVoIPPushes], PKPushRegistry.m:349
Key Observations:
VoIP pushes arrive and are delivered to the app.
In foreground, some methods work and CallKit UI sometimes appears.
In background/killed state, app is always terminated before CallKit UI shows.
Logs confirm the system requires CallKit to be reported immediately inside pushRegistry(_:didReceiveIncomingPushWith:for:completion:).
Steps to Reproduce:
Run the app with VoIP + CallKit integration.
Put app in background (or kill it).
Send a VoIP push.
Observe system logs and crash:
callservicesd: Delivering 1 VoIP payload(s) to application
UrgiDoctor: Apps receiving VoIP pushes must post an incoming call via CallKit...
error: Killing VoIP app because it failed to post an incoming call in time.
Expected Behavior:
On receiving a VoIP push, CallKit UI (Accept / Decline screen) should always appear.
App should not be killed if reportNewIncomingCall is called in time.
Actual Behavior:
CallKit UI never appears in background/killed state.
App is force-terminated by iOS before user can accept/decline the call.
Request:
Guidance on the correct sequence for calling reportNewIncomingCall and completionHandler() in pushRegistry.
Clarification if any changes in iOS 17/18 affect PushKit + CallKit behavior.
Best practices for ensuring CallKit UI always appears reliably after a VoIP push.
Environment:
iOS 18.5 Simulator + Device
Xcode 16.4
Using PushKit + CallKit with VoIP entitlement
We added the com.apple.developer.background-tasks.continued-processing.gpu key to the entitlement file and set it to true, but BGTaskScheduler.supportedResources does not include gpu. How can we configure it to obtain permission for GPU access in the background?
Test device: iPhone 16 Pro Max, iOS 26 release version.
I’m developing a iOS VPN app, and I need to execute a task in the main app even when it’s in the background or killed state. I know the Network Extension continues running during those times. Is there a way for the extension to immediately notify the app or trigger a task on the app side?
Hello im creating an expo module using this new API, but the problem i found currently testing this functionality is that when the task fails, the notification error doesn't go away and is always showing the failed task notification even if i start a new task and complete that one.
I want to implement this module into the production app but i feel like having always the notification error might confuse our users or find it a bit bothersome.
Is there a way for the users to remove this notification?
Best regards!
I got users feed back, sometimes they seem the launch screen after active from background, and the launch screen show more longer than the cold launch. I check the app's log, when this issue happens, it displays a view controller named 'STKPrewarmingViewController', and disappears after about 5 seconds. And form the normal users, app don't have same behavior. It seems app need prewarming after back from background, why?
Devices System version: iOS 18.4, app build with Xcode 16.
How to fixed this issues?
Thanks!
Testing Environment:
iOS: 26.0 Beta 7
Xcode: Beta 6
Description:
We are implementing the new BGContinuedProcessingTask API introduced in iOS 26. We have followed the official documentation and WWDC session guidance to configure our project.
The Background Modes (processing) and Background GPU Access capabilities have been added in Xcode.
The com.apple.developer.background-tasks.continued-processing.gpu entitlement is present and set to in the .entitlements file.
The provisioning profile details viewed within Xcode explicitly show that the "Background GPU Access" capability and the corresponding entitlement are included.
Despite this correct configuration, when running the app on supported hardware (iPhone 16 Pro), a call to BGTaskScheduler.supportedResources.contains(.gpu) consistently returns false.
This prevents us from setting request.requiredResources = .gpu. As a result, when the BGContinuedProcessingTask starts without the GPU resource flag, our internal Metal-based exporter attempts to access the GPU and is terminated by the system, throwing an IOGPUMetalError: Insufficient Permission (to submit GPU work from background).
We have performed extensive debugging, including a full reset of the provisioning profile (removing/re-adding capabilities, toggling automatic signing, cleaning build folders, and reinstalling the app), but the issue persists. This strongly suggests a bug in the iOS 26 beta where the runtime is failing to correctly validate a valid entitlement.
Additionally, we've observed inconsistent behavior across devices. On an A16-based iPad, the task submits successfully (BGTaskScheduler.submit does not throw an error), but the launch handler is never invoked by the system. On the iPhone 16 Pro, the handler is invoked, but we encounter the supportedResources issue described above. This leads us to ask for clarification on the exact hardware requirements for this feature. We hypothesize that it may be limited to devices that support Apple Intelligence (A17 Pro and newer). Could you please confirm this and provide official documentation on the device support criteria?
Steps to Reproduce:
Create a new Xcode project.
In Signing & Capabilities, add "Background Modes" (with "Background processing" checked) and "Background GPU Access".
Add a permitted identifier (e.g., "com.company.test.*") to BGTaskSchedulerPermittedIdentifiers in Info.plist.
In application(_:didFinishLaunchingWithOptions:) or a ViewController's viewDidLoad, log the result of BGTaskScheduler.shared.supportedResources.contains(.gpu).
Build and run on a physical, supported device (e.g., iPhone 16 Pro).
Expected Results:
The log should indicate that BGTaskScheduler.shared.supportedResources.contains(.gpu) returns true.
Actual Results:
The log shows that BGTaskScheduler.shared.supportedResources.contains(.gpu) returns false.
Hi, I have a couple questions about background app refresh. First, is the function RefreshAppContentsOperation() where to implement code that needs to be run in the background? Second, despite importing BackgroundTasks, I am getting the error "cannot find operationQueue in scope". What can I do to resolve that? Thank you.
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "peaceofmindmentalhealth.RoutineRefresh")
// Fetch no earlier than 15 minutes from now.
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh: \(error)")
}
}
func handleAppRefresh(task: BGAppRefreshTask) {
// Schedule a new refresh task.
scheduleAppRefresh()
// Create an operation that performs the main part of the background task.
let operation = RefreshAppContentsOperation()
// Provide the background task with an expiration handler that cancels the operation.
task.expirationHandler = {
operation.cancel()
}
// Inform the system that the background task is complete
// when the operation completes.
operation.completionBlock = {
task.setTaskCompleted(success: !operation.isCancelled)
}
// Start the operation.
operationQueue.addOperation(operation)
}
func RefreshAppContentsOperation() -> Operation {
}