Background Tasks

RSS for tag

Request the system to launch your app in the background to run tasks using Background Tasks.

Posts under Background Tasks tag

148 Posts

Post

Replies

Boosts

Views

Activity

BGContinuedProcessingTask compatibility with background URLSession
My app does really large uploads. Like several GB. We use the AWS SDK to upload to S3. It seemed like using BGContinuedProcessingTask to complete a set of uploads for a particular item may improve UX as well as performance and reliability. When I tried to get BGContinuedProcessingTask working with the AWS SDK I found that the task would fail after maybe 30 seconds. It looked like this was because the app stopped receiving updates from the AWS upload and the task wants consistent updates. The AWS SDK always uses a background URLSession and this is not configurable. I understand the background URLSession runs in a separate process from the app and maybe that is why progress updates did not continue when the app was in the background. Is it expected that BGContinuedProcessingTask and background URLSession are not really compatible? It would not be shocking since they are 2 separate background APIs. Would the Apple recommendation be to use a normal URLSession for this, in which case AWS would need to change their SDK? Or does Apple think that BGContinuedProcessingTask should just not be used with uploads? In other words use an upload specific API. Thanks!
2
0
84
Aug ’25
Testing and Debugging Code Running in the Background
I regularly bump into folks confused by this issue, so I thought I’d collect my thoughts on the topic into a single (hopefully) coherent post. If you have questions or comments, put them in a new thread here on the forums. Feel free to use whatever subtopic and tags that apply to your situation, but make sure to add the Debugging tag so that I see your thread go by. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Testing and Debugging Code Running in the Background I regularly see questions like this: My background code works just fine in Xcode but fails when I download the app from the App Store. or this: … or fails when I run my app from the Home screen. or this: How do I step through my background code? These suggest a fundamental misunderstanding of how the debugger interacts with iOS’s background execution model. The goal of this post is to explain that misunderstanding so that you can effectively test and debug background code. Note The focus of this post is iOS. The advice here generally applies to any of iOS’s ‘child’ platforms, so iPadOS, tvOS, and so on. However, there will be some platform specific differences, especially on watchOS. This advice here doesn’t apply to macOS. It’s background execution model is completely different than the one used by iOS. Understand the Fundamentals The key point to note here is that the debugger prevents your app from suspending. This has important consequences for iOS’s background execution model. Normally: iOS suspends your app when it’s in the background. Once your app is suspended, it becomes eligible for termination. The most common reason for this is that the system wants to recover memory, but it can happen for various other reasons. For example, the system might terminate a suspended app in order to update it. Under various circumstances your app can continue running after moving to the background. A great example of this is the continued processed task feature, introduced in iOS 26 beta. Alternatively, your app can be resumed or relaunched in the background to perform some task. For example, the region monitor feature of Core Location can resume or relaunch your app in the background when the user enters or leaves a region. If no app needs to be executing, the system can sleep the CPU. None of this happens in the normal way if the debugger is attached to your app, and it’s vital that you take that into account when debugging code that runs in the background. An Example of the Problem For an example of how this can cause problems, imagine an app that uses an URLSession background session. A background session will resume or relaunch your app in the background when specific events happen. This involves two separate code paths: If your app is suspended, the session resumes it in the background. If your app is terminated, it relaunches it in the background. Neither code path behaves normally if the debugger is attached. In the first case, the app never suspends, so the resume case isn’t properly exercised. Rather, your background session acts like it would if your app were in the foreground. Normally this doesn’t cause too many problems, so this isn’t a huge concern. On the other hand, the second case is much more problematic. The debugger prevents your app from suspending, and hence from terminating, and thus you can’t exercise this code path at all. Seek Framework-Specific Advice The above is just an example, and there are likely other things to keep in mind when debugging background code for a specific framework. Consult the documentation for the framework you’re working with to see if it has specific advice. Note For URLSession background sessions, check out Testing Background Session Code. The rest of this post focuses on the general case, offering advice that applies to all frameworks that support background execution. Run Your App Outside of Xcode When debugging background execution, launch your app from the Home screen. For day-to-day development: Run the app from Xcode in the normal way (Product > Run). Stop it. Run it again from the Home screen. Alternatively, install a build from TestFlight. This accurately replicates the App Store install experience. Write Code with Debugging in Mind It’s obvious that, if you run the app without attaching the debugger, you won’t be able to use the debugger to debug it. Rather: Extract the core logic of your code into libraries, and then write extensive unit tests for those libraries. You’ll be able to debug these unit tests with the debugger. Add log points to help debug your integration with the system. Treat your logging as a feature of your product. Carefully consider where to add log points and at what level to log. Check this logging code into your source code repository and ship it — or at least the bulk of it — as part of your final product. This logging will be super helpful when it comes to debugging problems that only show up in the field. My general advice is that you use the system log for these log points. See Your Friend the System Log for lots of advice on that front. One of the great features of the system log is that disabled log points are very cheap. In most cases it’s fine to leave these in your final product. Attach and Detach In some cases it really is helpful to debug with the debugger. One option here is to attach to your running app, debug a specific thing, and then detach from it. Specifically: To attach to a running app, choose Debug > Attach to Process > YourAppName in Xcode. To detach, choose Debug > Detach. Understand Force Quit iOS allows users to remove an app from the multitasking UI. This is commonly known as force quit, but that’s not a particularly accurate term: The multitasking UI doesn’t show apps that are running, it shows apps that have been run by the user. The UI shows recently run apps regardless of whether they’re in the foreground, running in the background, suspended, or terminated. So, removing an app from the UI may not actually quit anything. Removing an app 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. Note In some circumstances iOS will not honour this flag. The exact cases where this happens are not documented and have changed over time. Keep these behaviours in mind as you debug your background execution code. For example, imagine you’re trying to test the URLSession background relaunch code path discussed above. If you force quit your app, you’ll never hit this code path because iOS won’t relaunch your app in the background. Rather, add a debug-only button that causes your app to call exit. IMPORTANT This suggestion is for debugging only. Don’t include a Quit button in your final app! This is specifically proscribed by QA1561. Alternatively, if you’re attached to your app with Xcode, simply choose Product > Stop. This is like calling exit; it has no impact on your app’s ability to run in the background. Test With Various Background App Refresh Settings iOS puts users in control of background execution via the options in Settings > General > Background App Refresh. Test how your app performs with the following settings: Background app refresh turned off overall Background app refresh turned on in general but turned off for your app Background app refresh turned on in general and turned on for your app IMPORTANT While these settings are labelled Background App Refresh, they affect subsystems other than background app refresh. Test all of these cases regardless of what specific background execution feature you’re using. Test Realistic User Scenarios In many cases you won’t be able to fully test background execution code at your desk. Rather, install a TestFlight build of your app and then use the device as a normal user would. For example: To test Core Location background execution properly, actual leave your office and move around as a user might. To test background app refresh, use your app regularly during the day and then put your device on charge at night. Testing like this requires two things: Patience Good logging The system log may be sufficient here, but you might need to investigate other logging solutions that are more appropriate for your product. These testing challenges are why it’s critical that you have unit tests to exercise your core logic. It takes a lot of time to run integration tests like this, so you want to focus on integration issues. Before starting your integration tests, make sure that your unit tests have flushed out any bugs in your core logic. Revision History 2025-08-12 Made various editorial changes. 2025-08-11 First posted.
0
0
116
Aug ’25
[iOS 26 beta] UIScene migration with loadFileURL:allowingReadAccessToURL: has partial rendering for app BG launch
We're currently migrating from AppDelegate to UISceneDelegate due to console warnings . Our application's UI, which is built on a single webpage, functions correctly when launched in the foreground after this migration. However, we've encountered an issue with partial rendered UI components when launching the application from the background, such as upon receiving a VoIP call. During a background launch, the following delegate calls occur before the client attempts to load a local webpage: [08/07 16:25:49:037][ 0x101ea3910]<ALA_SIGNAL>: [OS-PLT] Exit -[AppDelegate application:didFinishLaunchingWithOptions:] [08/07 16:25:49:084][ 0x10c0c4140]<PushToTalk> [Pushnotif] [] <ALA_SIGNAL>: [OS-CCF] Enter -[PushNotificationManager pushRegistry:didReceiveIncomingPushWithPayload:forType:withCompletionHandler:] [08/07 16:25:49:098][ 0x101ea3910]Begin -[SceneDelegate scene:willConnectToSession:options:] [08/07 16:25:49:098][ 0x101ea3910]Exit -[SceneDelegate scene:willConnectToSession:options:] As part of client login process we load the index page in WebKit here: [08/07 16:25:50:977][ 0x101ea3910]<ALA_SIGNAL>: [PLT-OS] Enter -[SceneDelegate loadUI:] [UI Launch Reason = 1] Code: NSString *path = [[NSBundle mainBundle]pathForResource:@"index" ofType:@"html" inDirectory:@"www"]; NSURL *urlReq = [NSURL fileURLWithPath:path]; [webView loadFileURL:urlReq allowingReadAccessToURL:urlReq]; The problem we're observing is that the webpage is only partially rendering in this background launch scenario (Seen after brought to FG). Any insights or assistance you can provide would be greatly appreciated.
2
0
192
Aug ’25
Background Modes, ScreenTime API
I’m attempting to run Apple’s ScreenTime API while my app is in the background When debugging on a device my background restrictions functionality works, but on TestFlight it does not. This is the error message when analyzing the device in XCodes Console BackgroundTaskSuspended. Background entitlement: NO When the proper entitlements are added this error doesn't allow for the build to be uploaded to TestFlight. Provisioning profile "iOS Team Provisioning Profile: com.***.***" doesn't include the UIBackgroundModes entitlement. I have the proper entries in the “Signing and Capabilities” of the project, but my functionality will not run in the background when the app is not launched. I just need a function to run that calls Apple's ScreenTime API while my app is in the background. Other apps have achieved the functionality I’m looking for so I know it’s possible, but this is the roadblock I’m running into.
2
0
132
Aug ’25
Problem receiving Remote Notification in the background after Review Rejected
I created an app. One if its functionalities is receive Remote Notification in the background, while app is monitoring Significant Location Changes (SLC). This functionality worked fine. I was receiving these notifications correctly. Sometimes instantly, sometime with small or large delay. And then I send the app for review. It was rejected with 3 remarks: The app or metadata includes information about third-party platforms that may not be relevant for App Store users, who are focused on experiences offered by the app itself (I wrote that app communication works both for iOS and Android.) The app declares support for audio in the UIBackgroundModes key in your Info.plist but we are unable to locate any features that require persistent audio. EULA (End User License Agreement) is missing for in-app purchases. After the rejection the app is no longer receiving these notifications. They are there, since the app receives them, when I open app, or significant location change is detected. It also works, when I run the app directly from Xcode (in debug mode), not from TestFlight nor in Sandbox. It seem to me like Apple somehow spoiled my background capabilities on purpose or accidentally. Is it possible? What can I do with it? Is it the case that I should just fix the review remarks and send the app back to review, and once the app passes it, it will work again? Or should I not count on it? Any suggestions? I asked Apple using: https://developer.apple.com/contact/topic/#!/topic/select but so far no response.
2
0
129
Aug ’25
Reliable 30-minute background data fetching for safety-critical monitoring app?
I'm developing a safety-critical monitoring app that needs to fetch data from government APIs every 30 minutes and trigger emergency audio alerts for threshold violations. The app must work reliably in background since users depend on it for safety alerts even while sleeping. Main Challenge: iOS background limitations seem to prevent consistent 30-minute intervals. Standard BGTaskScheduler and timers get suspended after a few minutes in background. Question: What's the most reliable approach to ensure consistent 30-minute background monitoring for a safety-critical app where missed alerts could have serious consequences? Are there special entitlements or frameworks for emergency/safety applications? The app needs to function like an alarm clock - working reliably even when backgrounded with emergency audio override capabilities.
1
0
512
Jul ’25
Background GPU Access availability
I would love to use Background GPU Access to do some video processing in the background. However the documentation of BGContinuedProcessingTaskRequest.Resources.gpu clearly states: Not all devices support background GPU use. For more information, see Performing long-running tasks on iOS and iPadOS. Is there a list available of currently released devices that do (or don't) support GPU background usage? That would help to understand what part of our user base can use this feature. (And what hardware we need to test this on as developers.) For example it seems that it isn't supported on an iPad Pro M1 with the current iOS 26 beta. The simulators also seem to not support the background GPU resource. So would be great to understand what hardware is capable of using this feature!
4
0
824
Jul ’25
BGProcessingTaskRequest executing even after force-quit from App Switcher
Hello, I have a question regarding the behavior of BGProcessingTaskRequest when the app is force-quit by the user via the App Switcher. Based on common understanding and various discussions — including the following Apple Developer Forum threads: Waking up an iOS app after app is … | Apple Developer Forums Will BGAppRefreshTaskRequest will … | Apple Developer Forums Background fetch after app is forc… | Apple Developer Forums …it is widely understood that iOS prevents background execution (such as background fetch, push notifications, or BGTaskScheduler) after a user force-quits an app via the App Switcher. However, in my app, I have observed that a scheduled BGProcessingTaskRequest still executes even after the app has been explicitly terminated via App Switcher. The task is scheduled using submit(_:error:), and it is clearly running some time after the app has been closed by the user. That said, the task does run, but it appears to operate under tighter constraints — for example, it may be allowed to run for a shorter duration, and network requests appear to be more restricted compared to when the app is not force-quit. My questions are: Are there any documented or undocumented exceptions that allow this kind of behavior after force-quit? Could this be a bug or a behavior change in recent iOS versions? (I am observing this on iOS 18.3, 18.4, and 18.5) Any insights, experiences, or clarifications from Apple engineers or fellow developers would be greatly appreciated. Thank you!
5
0
122
Jul ’25
Does BGAppRefreshTask require an internet connection?
Basically the title. I am trying to implement a local notification to trigger, regardless of internet connection, around 3-5pm if a certain array in the app is not empty to get the user to sync unsaved work with the cloud. I wanted to used the BGAppRefreshTask as I saw it was lightweight and quick for just posting a banner notification but after inspecting it in the console, it looks like it needs internet connection to trigger. Is this the case or am I doing something wrong? Should I be using the BGProcessingTask instead?
1
0
57
Jul ’25
WebSocket connection in background triggered by BLE accessory
Hello everyone, We are building an iOS app using React Native that connects to a custom Bluetooth Low Energy (BLE) accessory. The accessory continuously sends small chunks of audio data to the app through BLE (basically every time the user speaks), which are then streamed in real time to our server via WebSocket for transcription and processing. We need to know if the following behavior is allowed by iOS runtime and App Store review policies: Can the app open a WebSocket connection in the background (not permanently, just briefly, several times a day) triggered by BLE activity from a registered accessory? Is there a limit to this? Clarifications: The app is not expected to remain permanently awake. Only during accessory-triggered events. WebSocket is required due to the real-time nature of streaming STT and delivering quick responses (via notifications). If allowed, are there any specific Info.plist declarations or entitlements we must include? Thanks in advance! Fran
5
0
197
Jul ’25
Background Modes for Audio Playback
Summary: I'm developing an iOS audio app in Flutter that requires background audio playback for long-form content. Despite having a paid Apple Developer Program account, the "Background Modes" capability does not appear as an option when creating or editing App IDs in the Developer Portal, preventing me from enabling the required com.apple.developer.background-modes entitlement. Technical Details: In the app that I am developing, users expect uninterrupted playback when app is backgrounded or device is locked similar to Audible, Spotify, or other audio apps that continue playing in background The Problem: When building for device testing or App Store submission, Xcode shows: Provisioning profile "iOS Team Provisioning Profile: com.xxxxx-vxxx" doesn't include the com.apple.developer.background-modes entitlement. However, the "Background Modes" capability is completely missing from the Developer Portal when creating or editing any App ID. I cannot enable it because the option simply doesn't exist in the capabilities list. What I've Tried: Multiple browsers/devices: Safari, Chrome, Firefox, incognito mode, different computers Account verification: Confirmed paid Individual Developer Program membership is active New App IDs: Created multiple new App IDs - capability never appears for any of them Documentation review: Followed all Apple documentation for configuring background execution modes Different regions: Tried changing portal language to English (US) Cache clearing: Logged out, cleared cookies, tried different sessions Apple Support Response: Contacted Developer Support (Case #102633509713). Received generic documentation links and was directed to Developer Forums rather than technical escalation. Has anyone else experienced the "Background Modes" capability missing from their Developer Portal? Has anyone successfully used the App Store Connect API to add background-modes when the GUI doesn't show it? What's the proper escalation path when Developer Support provides generic responses instead of technical assistance? Things I have attempted to solve this: audio_service package: Implemented as potential workaround, but still requires the system-level entitlement Manual provisioning profiles: Cannot create profiles with required entitlement if capability isn't enabled on App ID Other perhaps important facts about the environment where I am building the app: macOS Sonoma Xcode 15.x Flutter 3.5.4+ Apple Developer Program (Individual, paid)
0
0
86
Jul ’25
Maximise background update on WatchOS
I'm looking to maximise my Watch app's widget to be as up to date as possible. If we imagined the app was a simple step counter, and we wanted to display the users count as up to date as possible. We can conclude: We don't care about widget timelines beyond the current entry as we can't predict the future! We need to refresh the count as often as possible The refresh should be very quick with a straightforward HealthKit query, no networking or heavy work needed. We will assume the user has the complication/widget on their active Watch face. With the standard WidgetKit APIs we can expire the timeline after 15 minutes and in my experimentation a Watch app can usually update its widget timeline at that frequency if it's on the Watch face. I'm experimenting with two methods to try and improve refreshes further A user's step count might not have recently changed when the timeline update is called. I was therefore looking into the HealthKit enableBackgroundDelivery API (which requires the HealthKit Background Delivery entitlement to be enabled) to get updates limited to once an hour from a HKObserverQuery, I can then call the WidgetCenter.shared.reloadAllTimelines() from there. WatchOS also support the BGAppRefreshTaskRequest(identifier:"") and .backgroundTask(.appRefresh) APIs. I can request updates once every 15 minutes here too and then call the WidgetCenter.shared.reloadAllTimelines(). With option 1, this update opportunity is great as it will specifically update when there's new steps so even once an hour this would be helpful (A real shame to be limited to once an hour even if this used up WidgetKit standard reload budgets: FB13879817, FB11677132, FB10016177). But I can't determine if this update takes away one of the standard timeline expiration updates that already run 4 times an hour? Could I observe additional Health types to get additional updates? Do I need the Background Modes Capability as well as the HealthKit Background Delivery for this in Xcode or just the HealthKit one? With option 2, I can't find a suitable option in the (short) list of supported background modes in Xcode. Does not selecting any mean my app will get 0 refreshes from this route and so should not be implemented in my use case?
3
1
123
Jun ’25
Called endBackgroundTask but not working
When my app enter to background, I start a background task, and when Expiration happens, I end my background task. The code likes below: backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ dispatch_async(dispatch_get_main_queue(), ^{ if (backgroundTask != UIBackgroundTaskInvalid) { [[UIApplication sharedApplication] endBackgroundTask:backgroundTask]; backgroundTask = UIBackgroundTaskInvalid; [self cancel]; } }); }]; When the breakpoint is triggered at the endBackgroundTask line, I also get the following log: [BackgroundTask] Background task still not ended after expiration handlers were called: <UIBackgroundTaskInfo: 0x282d7ab40>: taskID = 36, taskName = Called by MyApp, from MyMethod, creationTime = 892832 (elapsed = 26). This app will likely be terminated by the system. Call UIApplication.endBackgroundTask(:) to avoid this. The log don't appear every time, so why is that? Is there something wrong with my code?
3
0
2.8k
Jun ’25
Background or Foreground
Hi Team! Has anyone found a reliable way to detect CarPlay connection without the app needing to be in the foreground? I’m exploring a concept where, for example, as someone nears home while driving, a prompt appears on the CarPlay screen asking “Would you like to turn on the lights / open garage?” triggered by proximity and CarPlay connection. Would be cool to have it work automatically, but knowing you're in the car is kind of important. From what I can see, apps can’t reliably detect CarPlay connection unless they’re actively open on the CarPlay screen. Most background detection methods (like external screen connect notifications) appear deprecated. That is, unless you're specifically approved as a "messaging" or "navigation" app that appear to get special privilages to send alerts from the background. If I send an alert (or poll Carplay periodically) it just gives silent/dead response. Is there any approach, framework, entitlement, or UI pattern that could allow a passive trigger or background detection while driving with CarPlay connected? I can't see any way to bring an app to the foreground either. Not looking to abuse any rules... just want to understand if anyone’s found a clean, approved workaround. Thanks in advance!
0
0
69
Jun ’25
XCFramework Location Behavior Differs from Standalone App in Background/Sleep Mode
Hi Apple Dev Team & Community, We’ve encountered an issue with background location updates when using an XCFramework we’ve built from our main app. Context: We have a standalone app called TravelSafely that reliably performs background location updates and alerts, even during sleep mode. From this app, we extracted some core functionality into an XCFramework, including location management, and provided it as an SDK to a client. We created a demo app to test this SDK in isolation. Problem: In the demo app, we notice that location updates work fine in the foreground. However, in the background or sleep mode, location updates sometimes stop completely. When we bring the app to the foreground again, location resumes. This does not happen in the original standalone app. What We’ve Already Checked: UIBackgroundModes includes location Info.plist has the required permissions Location is started correctly using startUpdatingLocation We maintain strong references and use background tasks as needed Question: Why would an app using a binary XCFramework (with location logic) behave differently from the original app in terms of background execution? Is there any known issue or recommendation when working with SDKs/XCFrameworks that need to manage background tasks and location updates? Any insights or recommendations to maintain proper background behavior would be highly appreciated. Thank you!
10
0
96
Jun ’25
Avoiding Shortcut Intent Timeout When Uploading or Downloading Large Files
Hey everyone, I have an issue I'm running into – maybe someone has the expertise to help! I've created an app that adds Intents to the Shortcuts app, to interact with S3-compatible object storage. Everything works fine, until you decide to upload/download a large file, that your internet connection cannot handle in the ~30-second intent timeout. I've explored uploading files with a background task which seems to work somehow, but the bigger issue would be downloading larger files, as other parts of the subsequent shortcut may rely on it. To the question: Is there some way of increasing the timeout for a shortcuts intent, or a way to "trick" shortcuts into letting my custom intents download/upload files without timing out? Thanks so much!
0
0
67
Jun ’25
iOS 18.4 - HomeKit actions from AppIntent fail when triggered from Widget
Hi all, Since updating to iOS 18.4, I'm experiencing a regression with AppIntents triggered from Widgets. In my app, I use AppIntents inside a WidgetKit extension to control HomeKit devices. This setup was working perfectly up to iOS 18.3. However, starting with iOS 18.4, when the AppIntent is triggered from the widget and the main app is not running, the action fails with this error: Error Domain=HMErrorDomain Code=80 "Missing entitlement for API." UserInfo={ NSLocalizedFailureReason=Handler does not support background access, NSLocalizedDescription=Missing entitlement for API. } Interestingly, the exact same AppIntent works fine if the app is still alive in the background — it seems like the failure only occurs when the intent is handled by the widget process. This looks like a behavior change or new restriction introduced in iOS 18.4. Has anyone experienced the same? Is there a new entitlement needed, or a recommended workaround? Thanks in advance!
3
2
209
Jun ’25
Real-time audio application on locked device
I would like to inquire about the feasibility of developing an iOS application with the following requirements: The app must support real-time audio communication based on UDP. It needs to maintain a TCP signaling connection, even when the device is locked. The app will run only on selected devices within a controlled (closed) environment, such as company-managed iPads or iPhones. Could you please clarify the following: Is it technically possible to maintain an active TCP connection when the device is locked? What are the current iOS restrictions or limitations for background execution, particularly related to networking and audio? Are there any recommended APIs or frameworks (such as VoIP, PushKit, or Background Modes) suitable for this type of application?
1
0
98
Jun ’25
Location streaming onto Live Activity
Hello forum, I want to keep my app running in the background after user swaps up, for the purpose of workout tracking. start up the task and continuously receipt GPS updates process the location data show the data on a live activity Two examples Strava paddlelogger Question: Does this mean, these two apps would just pause when the .backgroundTimeRemaining becomes 0? How does a workout app "work" in background mode, do I need to handle budget running out?
2
0
79
Jun ’25