General:
DevForums tag: Background Tasks
Background Tasks framework documentation
UIApplication background tasks documentation
ProcessInfo expiring activity documentation
watchOS background execution documentation
WWDC 2020 Session 10063 Background execution demystified — This is critical resource. Watch it!
WWDC 2022 Session 10142 Efficiency awaits: Background tasks in SwiftUI
iOS Background Execution Limits DevForums post
UIApplication Background Task Notes DevForums post
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
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
135 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I've been seeing a high number of BGTaskScheduler related crashes, all of them coming from iOS 18.4. I've encountered this myself once on launch upon installing my app, but haven't been able to reproduce it since, even after doing multiple relaunches and reinstalls. Crash report attached at the bottom of this post.
I am not even able to symbolicate the reports despite having the archive on my MacBook:
Does anyone know if this is an iOS 18.4 bug or am I doing something wrong when scheduling the task? Below is my code for scheduling the background task on the view that appears when my app launches:
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
#if !os(macOS)
let request = BGAppRefreshTaskRequest(identifier: "notifications")
request.earliestBeginDate = Calendar.current.date(byAdding: .hour, value: 3, to: Date())
do {
try BGTaskScheduler.shared.submit(request)
Logger.notifications.log("Background task scheduled. Earliest begin date: \(request.earliestBeginDate?.description ?? "nil", privacy: .public)")
} catch let error {
// print("Scheduling Error \(error.localizedDescription)")
Logger.notifications.error("Error scheduling background task: \(error.localizedDescription, privacy: .public)")
}
#endif
...
}
2025-02-23_19-53-50.2294_+0000-876d2b8ec083447af883961da90398f00562f781.crash
I am developing an App that will enable voice calls between users through webrtc. When the user opens the App and switches the App to the background, the user will receive the incoming call notification through Silent Push Notifications (not PushKit).
My question is as follows,
If set UIBackgroundModes to voip and do not use PushKit and CallKit, will this cause the background App to be unable to use webrtc voice calls (requires network, microphone, and audio permissions)?
Can I set UIBackgroundModes = audio combined with AVAudioSession playAndRecord instead of setting UIBackgroundModes to voip, so that I can use the microphone and audio in the background to implement webrtc voice calls?
Thanks for your help.
When I run my app with XCode on my iPhone, and then moved into the background, I'm getting a EXC_BREAKPOINT exception after a few minutes, seemingly when iOS attempts to call my app with a BGAppRefreshTask:
Thread 23 Queue: com.apple.BGTaskScheduler (com.mycompany.MyApp.RefreshTask) (serial)
0 _dispatch_assert_queue_fail
12 _pthread_wqthread
Enqueued from com.apple.duet.activityscheduler.client.xpcqueue (Thread 23)
0 dispatch_async
20 start_wqthread
I can't quite understand the reason from this crash. In the background task, I'm attempting to update live activities. In the process, it might encounter code that calls MainActor and manipulate @Observable objects. Might that be the reason?
we have three problem when using the push notification on Live Activity.
1. What is the specific callback strategy for the activityUpdates property in ActivityKit?
We found that in actual user scenarios, there is a probability that we may not receive callbacks. From the community experience, there are some resource optimization strategies that do not perform callbacks. From this perspective, the explanation is kind of vague. Is there any clear feedback to understand why callbacks are performed/not performed?
2.what is the specific description of the wake-up strategy, when background app receive Live Activity offline start Push?
From community experience, we can see that the system may wake up for a duration of 0-30s due to resource optimization strategies, or not wake up/not deal with it. Is there an official description of the wake-up strategy? or we also have to follow this description:
Wake up of apps using content-available pushes are heavily throttled. You can expect 1-2 wakeup per hour as a best case scenario in the hands of your users. so this cannot be assumed to be a reliable wake-up on demand mechanism for an app.
3 How can we determine user have selected (allow or always allow) of the Live Activity permission?
When we use real-time activity offline push, there are two system prompts in iOS:
the first prompt : allow and disallow real-time activity
the second prompt : always allow and disallow
Is there an interface that can directly determine which permission the user has chosen (allow/always allow)? (By the way, we can get disallow status).
At present, we haven't seen any interface in the official documentation/interface that can determine (allow/always allow). The difference here will affect the generation of Update Token. Without Update Token, we can not update our activity instance.
I’m facing an issue with iOS that I hope someone can help with. I developed an app a few years ago that records GPS tracks. Up until recently, everything worked fine—even when the app was running in the background, the recording continued without problems.
However, since releasing an update compiled after the iOS 18 release, users have reported that background tracking no longer works. I’ve reviewed the iOS documentation but haven’t found any relevant changes or solutions. Before the newly compiled release the app was working well on iOS 18 devices as well.
Some users have reported that switching to the location permission from "When Using the App" to "Always" solved the issue. This is not the case for all users.
Has anyone else encountered this issue? Any recommendations or insights on how to resolve it would be greatly appreciated.
Below you can see the code used for the location tracking. Before the issue happened the app was compiled with XCode 15.4. Now I am using XCode 16.2
locationManager.activityType = CLActivityType.fitness
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 3
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
if #available(iOS 11.0, *) {
locationManager.showsBackgroundLocationIndicator = true
}
locationManager.startUpdatingLocation()
if #available(iOS 17.0, *) {
// Create a CLBackgroundActivitySession object
backgroundActivitySession = CLBackgroundActivitySession()
}
Thanks in advance for your help!
Hello everyone,
I am currently working on a project for the health sector.
Basically we have some Bluetooth low energy devices that have a button.
When this button is pressed (usually for emergency situation), this event should alert our backend and therefore send help.
Is it technically possible to do this on IOS?
I am aware that apple have very strict restrictions in relation to background services, and after doing some research I found that it's impossible to run any custom code if the app is terminated by the user.
Is there a way to make a request for such special cases so that apple allows us to actually launch the app (or if not possible send a http request) when this beacon button is pressed (Of course with the bluetooth device already connected to the Iphone) even if the app is completely terminated.
Thanks :)
Any idea to achieve reliable periodic Bluetooth data retrieval on iOS, even when the app is closed or killed.
Hi I'm new to the forum,
I'm planning an app just for Apple watch, I would like to use bluetooth audio in background, how can I do it?
The messages I send via bluetooth stop as soon as the watch display turns off.
Thank you!
Nax
Our watch app, Regatta Timer, is a specialised countdown timer for sailing competitions. It is crucial that the beeps & haptics continue when 'wrist down' on alway on displays. We tried to enable this by adding 'background mode' but that only works in the Xcode Apple Watch simulator, not on an actual device with always on display. Any idea how we can get this working also on the Apple Watch device?
In ContentView.swift we currently added this code:
WKInterfaceDevice.current().play(sound)
}
but that doesnt work - regardless of adding , phase == .active`
or not.
STEPS TO REPRODUCE
Install on an ACTUAL DEVICE with always on display
start the countdown timer: beeps & sounds are OK (each minute,...)
do 'wrist down': the countdown timer continues on the dimmed display, but the sounds & haptics stop working until you raise your wrist to wake up the display.
My iOS application can execute a timer in the background on some devices, but it doesn't work on others.
I attached my raw data to this post. The raw data includes the device ID, the iPhone model, and the iOS version.
raw data:
Can someone help me, please!
I am considering to use the BGAppRefreshTask mechanism, and while I think I have read and understood all documentation and hints in this forum about it (especially the limitations), the one thing I do not understand is: how can I debug it? I cannot find a way to trigger the BGAppRefreshTask execution reliably and immediately. I would have expected the Xcode Debug->Simulate Background Fetch menu to do this for me, but it only sends the app into the background.
I am working with the unmodified (except for a few added print()) ColorFeed sample code project from Apple, which schedules a task 15min into the future when it goes to the background. Using a real device, I have not managed to trigger execution of the BGAppRefreshTask more often than once a day so far.
Surely, there must be a way to trigger it much more often solely for debugging and development purposes (I am totally happy with all restrictions for the final app).
So what detail am I missing here?
Hi,
I have requirement in iOS where application needs to run in the background
It can be a simple hello world program running in the background.
could you shed some light on what is the expected behaviour and is it allowed in iOS.
DESCRIPTION OF PROBLEM
Logs and data from our application indicate various errors that strongly suggest that our application is being launched in a state in which the device is likely locked. We are looking for guidance on how to identify, debug, reproduce, and fix these cases.
Our application does not use any of the common mechanisms for background activity, such as Background App Refresh, Navigation, Audio, etc.
Errors we get in our logs such as "authorization denied (code: 23)" when trying to access a file in our app's container on disk (a simple disk cache for data our application uses) strongly suggest that the device is operating in a state, such as being locked, where our application lacks the requisite permissions it would normally have during operation. Furthermore, attempts to access authentication information stored in the keychain also fails. We use kSecAttrAccessibleWhenUnlocked when accessing items we store in the keychain.
We have investigated "Prewarming", as well as our notification extension that helps process incoming push notifications, but cannot find any way to recreate this behavior.
Are there any steps Apple engineers can recommend to triage and debug this?
Some additional questions that would help us:
What are all of the symptoms that we can look for if prewarming escapes the intended execution context?
What are all of the circumstances in which we would be unauthorized to access the app’s documents/file directories even if it works correctly in normal operation?
STEPS TO REPRODUCE
Unfortunately, we are unable to forcibly reproduce this behavior in our application, so we're looking for guidance on how we might simulate this behavior in Xcode / Instruments.
Are there tools that Apple provides that would allow us to simulate certain behaviors like prewarming to verify our application's functionality?
Are there other reasons our application might be launched while the device is locked? Are there other reasons we would receive security errors when accessing the keychain or disk that are unrelated to the device being locked?
I am writing to address a concern regarding the background permission functionality in my app, which is critical for ensuring user safety as they navigate various terrains. This feature also enables users to smoothly record their navigation tracks for review after their activities. Recently, I've noticed that this functionality is not working as seamlessly as before.
Additionally, I observed that the app is not categorized under 'health and fitness'—could reclassifying it improve background activity? Before I delve into a detailed code review, I wanted to check if this issue might be related to sync or settings on the App Store side, such as permission configurations, app updates, or other related factors. Or, is it more likely an issue stemming from the app’s codebase?
I'm working on an application where, once the user starts driving, I need to periodically check their activity every 2.5 minutes (150 seconds) to determine whether they are still driving, walking, or have stopped. If they are still driving, I want to keep rescheduling the task until the user is no longer in a driving state.
Currently, I'm using startMonitoringSignificantLocationChanges to wake the app when the user's location changes, which works as expected. However, the activity detection stops after the first result is received, and I can't continue tracking the user's activity in the background (or after the app is killed from the app switcher).
Here's my approach:
After receiving a significant location change, I start tracking the user’s activity to check if they are driving or have stopped.
I reschedule this task every 2.5 minutes as long as the user remains in a driving state.
I need this process to run even when the app is in the background or terminated by the user.
Question: Is it possible to keep activity detection running periodically after receiving a location change, even when the app is in the background or terminated? What is the recommended way to implement this?
I would appreciate any suggestions or best practices for achieving this functionality.
Hi everyone,
We came an issue that, In some scenarios in our app we cannot fetch any resources from device (Photo and Contact).
One case we catched is putting app in background and spending time in other commonly used apps and coming back to our app cause this issue but there is a small chance that get this issue during using the application.
In cell, we are trying to fetch the image like this
imageFetchTask = Task {
let image = await CompositionRoot.shared.photosManager.image(requestType: .imageCollections, forId: photoAsset.photoId)
self.photoImageView.image(image)
}
and inner layers of this code we get the PHAsset and request image
PHAsset.firstAsset(for: id)
let manager = PHImageManager.default()
manager.requestImage(for: asset, targetSize: request.targetSize, contentMode: .aspectFill, options: request.options) { (image, info) in
continuation.resume(returning: image)
}
We figured out that issue not happening only in Photos also Contacts and
any web request. So any help according to this situation is well appreciated.
Thanks
I have an iOS app, watchOS app, and iOS Widget that shows the most recent data in the database.
The watch app sends data to the iOS app over the WCSession and is received in session(didReceiveMessage, replyHandler). After that data is processed, reloadAllTimelines() is called.
When running in Simulator or on device plugged in to debugger, it works, the widget updates when the app is closed (in background, even if force quit).
But when running TestFlight or App Store build, the data is still processed and saved to Core Data (I open the app and it's there), but the widget doesn't update.
It seems that reloadAllTimelines only works when the app is in foreground (at least in non debug builds). I dont have an iOS 17 device to check but I think this is a recent bug with iOS 18.
Hi everyone,
I’m encountering a recurring issue with my app submission, and I’d appreciate your insights. My app has been rejected due to Guideline 2.5.4 with the following feedback:
Guideline 2.5.4 - Performance - Software Requirements
The app continues to declare support for location in the UIBackgroundModes key in your Info.plist file but we are unable to locate any features besides employee tracking that require persistent location.
Using the location background mode for the sole purpose of tracking employees is not appropriate.
Please note we located the features of the app but the location background tracking of employees is not appropriate with this guideline.
Next Steps
If the app has a feature besides tracking employees that requires persistent location, reply to this message and let us know how to locate this feature. Otherwise, it would be appropriate to revise the app to include additional features for your users that require the persistent use of real-time location updates while the app is in the background
My App’s Use Case:
The app is designed to support events where users can check in and check out. Persistent location tracking is essential for the following:
1. During Events:
• Tracking users’ real-time location ensures they remain within the event boundaries.
• If a user exits the designated area, the system logs the occurrence for compliance and security purposes.
2. Workforce Monitoring:
• For work events, the app records working hours based on their presence within the event area.
• This ensures accurate logging of attendance and work durations.
Steps I’ve Taken:
• Limited Scope of Tracking: Persistent location tracking is active only during event check-in and check-out periods. Outside of these periods, tracking is disabled.
• User Consent: I’ve implemented clear permission requests and a privacy policy to explain how location data is used.
• Info.plist Configuration: I’ve declared the UIBackgroundModes key with location to support background tracking.
Despite these measures, my app continues to be rejected with the feedback above. I believe my app’s features align with the guidelines as the location tracking is directly tied to event functionality and user benefit.
Questions:
1. How can I better explain this use case to Apple’s review team to demonstrate compliance?
2. Are there any additional features or adjustments I should consider to ensure my app meets the guidelines?
3. Has anyone faced a similar issue with persistent location tracking, and how did you resolve it?
Thank you for your guidance and support!
I'm making a Safari extension for learning languages. I need speech synthesis for any language the user chooses to learn.
I initially tried to make this work within JavaScript, but Safari 18 doesn't reliably list voices for all languages on the web SpeechSynthesis API as described here: https://stackoverflow.com/questions/79179072/how-do-you-use-a-japanese-voice-with-speechsynthesis-in-safari-ios-18
As a workaround, I've had to use AVSpeechSynthesizer in SafariWebExtensionHandler (NSExtensionRequestHandling implementation for the extension). This works in the simulator but not on a real device. I've found this note from Apple in a StackOverflow reply:
"Safari extensions are very short-lived, hence not fit for audio playback or speech synthesis. Not being able to validate an app extension in Xcode with a manually-added plist entry for background audio is the designed behavior. The general recommendation is to synthesize speech using JavaScript in conjunction with the Web Speech API."
Unfortunately, the suggestion to use the Web Speech API is unsuitable as I just explained.
Is there a way to set up a background process in the host app that can do speech synthesis? The app extension would need a way to communicate with this process, and start it if it's not running. Is that possible?
I am trying to build a chat app. I am using FCM to deliver messages to my app accompanied by some custom data like the new message_data, deleted message_id and so on; each message will need to run the app in the background to do some background processing and local database syncing.
This continuous background processing is clearly not acceptable as APNs imposes a per-device limit on background push notifications . I am asking how can I push messages and actions payload without being throttled ?