Processes & Concurrency

RSS for tag

Discover how the operating system manages multiple applications and processes simultaneously, ensuring smooth multitasking performance.

Concurrency Documentation

Posts under Processes & Concurrency subtopic

Post

Replies

Boosts

Views

Activity

EXC_BREAKPOINT in BGAppRefreshTask
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?
2
1
463
Feb ’25
How to view documentation and example codes for Grand Central Dispatch for C
Hi, I am programming in C and would like to use Grand Central Dispatch for parallel computing (I mostly do physics based simulations). I remember there used to be example codes provided by Apple, but can't find those now. Instead I get the plain documentation. May anyone point me to the correct resources? It will be greatly appreciated. Thanks ☺.
2
0
126
Oct ’25
Possible to allow x code builds to run background processes for over 3 minutes
I have an app that I'm using for my own purposes and is not in the app store. I would like to run an http server in the background for more than the allotted 3 minutes to allow persistent communications with a connected Bluetooth device. The Bluetooth device would poll the service at intervals. Is this possible to do? This app does not need app store approval since it's only for personal use.
2
0
367
Feb ’25
Bluetooth work with BGTaskScheduler
Hi All, I'm working on an app that needs to connect to BLE device and on defined schedules download data from the device. the amount of data is segnificant and might take around a minute to download. we tought about utilizing both state restoration and preservation for app waking and scheduling (triggered by the ble peripheral) and BGTaskScheduler to schedule a task that will handle a long running task to manage the full data download. now, will this solution in general valid? isnt it a "hack" that goes around the 10s limit that state restoration enforces? i know there are limitations for BGTask (like when it runs, it might be terminated by the system etc) but considering that, can we proceed with this approach without breaching apple guidelines? thank you in advance!
2
0
150
Oct ’25
BGContinuedProcessingTask UI
When I use BGContinuedProcessingTask to submit a task, my iPhone 12 immediately shows a notification banner displaying the task’s progress. However, on my iPhone 15 Pro Max, there’s no response — the progress UI only appears in the Dynamic Island after I background the app. Why is there a difference in behavior between these two devices? Is it possible to control the UI so that the progress indicator only appears when the app moves to the background?
2
0
180
Oct ’25
SSMenuAgent consuming lots of CPU
My load average on a largely idle system is around 22, going up to 70 or so periodically; SSMenuAgent seems to be consuming lots of CPU (and, looking at spindump, it certainly seems busy), but... it's not happening on any other system whose screens I am observing. (Er, I know about load average limitations, the process is also consuming 70-98% CPU according to both top and Activity Monitor.) Since this machine (although idle) has our network extension, I'm trying to figure out if this is due to that, or of this is generally expected. Anyone?
2
0
423
May ’25
Do i need to free memory for C strings obtained from xpc_dictionary_get_string?
I am using C APIs for XPC communication. When my XPC server gets a xpc_dictionary as a message, I use xpc_dictionary_get_string to get the string which is of type const char*. Afterwards, when I try to free up the memory for the string, I get an error. I could not find any details on why this happens. Does XPC handle the lifecycle of these C strings ? I did some tests to see the behaviour. The following code snippet prints a string temp before and after releasing the dictionary memory. char* string = "dummy-string"; xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0); xpc_dictionary_set_string(dict, "str", string); const char* temp = xpc_dictionary_get_string(reply, "str"); printf("temp before release: %s\n", temp); xpc_release(reply); printf("temp after release: %s\n", temp); output: # temp before release: dummy-string # temp after release: I tried to free the variable temp before and after releasing dict . char* string = "dummy-string"; xpc_object_t dict = xpc_dictionary_create(NULL, NULL, 0); xpc_dictionary_set_string(dict, "str", string); const char* temp = xpc_dictionary_get_string(dict, "str"); printf("temp before release: %s\n", temp); free((void *)temp); // case 1 xpc_release(dict); // free((void *)temp); // case 2 printf("temp after release: %s\n", temp); in both the cases i got the output: # temp before release: dummy-string # app(18502,0x1f02fc840) malloc: Double free of object 0x145004a20 # app(18502,0x1f02fc840) malloc: *** set a breakpoint in malloc_error_break to debug # SIGABRT: abort # PC=0x186953720 m=0 sigcode=0 # signal arrived during cgo execution # ... # ...
2
0
416
Feb ’25
How to debug or ensure single resume calls for continuations at compile time or with tools like Instruments?
When using the continuation API, we're required to call resume exactly once. While withCheckedContinuation helps catch runtime issues during debugging, I'm looking for ways to catch such errors at compile time or through tools like Instruments. Is there any tool or technique that can help enforce or detect this requirement more strictly than runtime checks? Or would creating custom abstractions around Continuation be the only option to ensure safety? Any suggestions or best practices are appreciated.
2
0
420
Jan ’25
Background Assets Extension and DeviceCheck
Hi, I have some questions regarding the Background Assets Extension and DeviceCheck framework. Goal: Ensure that only users who have purchased the app can access the server's API without any user authentication using for example DeviceCheck framework and within a Background Assets Extension. My app relies on external assets, which I'm loading using the Background Assets Extension. I'm trying to determine if it's possible to obtain a challenge from the server and send a DeviceCheck assertion during this process within the Background Assets Extension. So far, I only receive session-wide authentication challenges—specifically NSURLAuthenticationMethodServerTrust in the Background Assets Extensio. I’ve tested with Basic Auth (NSURLAuthenticationMethodHTTPBasic) just for experimentation, but the delegate func backgroundDownload( _ download: BADownload, didReceive challenge: URLAuthenticationChallenge ) async -> (URLSession.AuthChallengeDisposition, URLCredential?) is never called with that authentication method. It seems task-specific challenges aren't coming through at all. Also, while the DCAppAttestService API appears to be available on macOS, DCAppAttestService.isSupported always returns false (in my testing), which suggests it's not actually supported on macOS. Can anyone confirm if that’s expected behavior?
2
0
142
May ’25
In the context of Live Activity, when app is launched into background due to some callback, should you wrap your work with background tasks?
I'm specifically focused on Live Activity, but I think this is somewhat a general question. The app could get a few callbacks when: There's a new payload (start, update, end) There's a new token (start, update) There's some other lifecycle event (stale, dismissed) Assuming that the user didn't force kill the app, would the app get launched in all these scenarios? When OS launches the app for a reason, should we wrap our tasks with beginBackgroundTask or that's unnecessary if we're expecting our tasks to finish within 30 seconds? Or the OS may sometimes be under stress and give you far less time (example 3 seconds) and if you're in slow internet, then adding beginBackgroundTask may actually come in handy?
2
0
83
Nov ’25
Flutter library that basically makes a call every "x" minutes if the app is in the background.
Hi everyone, could you help us? We implemented a Flutter library that basically makes a call every x minutes if the app is in the background, but when I generate the version via TestFlight for testing, it doesn't work. Can you help us understand why? Below is a more detailed technical description. Apple Developer Technical Support Request Subject: BGTaskScheduler / Background Tasks Not Executing in TestFlight - Flutter App with workmanager Plugin Issue Summary Background tasks scheduled using BGTaskScheduler are not executing when the app is distributed via TestFlight. The same implementation works correctly when running the app locally via USB/Xcode debugging. We are developing a Flutter application that needs to perform periodic API calls when the app is in the background. We have followed all documentation and implemented the required configurations, but background tasks are not being executed in the TestFlight build. App Information Field Value App Version 3.1.15 (Build 311) iOS Minimum Deployment Target iOS 15.0 Framework Flutter Flutter SDK Version ^3.7.2 Technical Environment Flutter Dependencies (Background Task Related) Package Version Purpose workmanager ^0.9.0+3 Main background task scheduler (uses BGTaskScheduler on iOS 13+) flutter_background_service ^5.0.5 Background service management flutter_background_service_android ^6.2.4 Android-specific background service flutter_local_notifications ^19.4.2 Local notifications for background alerts timezone ^0.10.0 Timezone support for scheduling Other Relevant Flutter Dependencies Package Version firebase_core 4.0.0 firebase_messaging (via native Podfile) sfmc (Salesforce Marketing Cloud) ^9.0.0 geolocator ^14.0.0 permission_handler ^12.0.0+1 Info.plist Configuration We have added the following configurations to Info.plist: UIBackgroundModes <key>UIBackgroundModes</key> <array> <string>location</string> <string>remote-notification</string> <string>processing</string> </array> ### BGTaskSchedulerPermittedIdentifiers ```xml <key>BGTaskSchedulerPermittedIdentifiers</key> <array> <string>br.com.unidas.apprac.ios.workmanager.carrinho_api_task</string> <string>br.com.unidas.apprac.ios.workmanager</string> <string>be.tramckrijter.workmanager.BackgroundTask</string> </array> **Note:** We included multiple identifier formats as recommended by the `workmanager` Flutter plugin documentation: 1. `{bundleId}.ios.workmanager.{taskName}` - Custom task identifier 2. `{bundleId}.ios.workmanager` - Default workmanager identifier 3. `be.tramckrijter.workmanager.BackgroundTask` - Plugin's default identifier (as per plugin documentation) ## AppDelegate.swift Configuration We have configured the `AppDelegate.swift` with the following background processing setup: ```swift // In application(_:didFinishLaunchingWithOptions:) // Configuration to enable background processing via WorkManager // The "processing" mode in UIBackgroundModes allows WorkManager to use BGTaskScheduler (iOS 13+) // This is required to execute scheduled tasks in background (e.g., API calls) // Note: User still needs to have Background App Refresh enabled in iOS settings if UIApplication.shared.backgroundRefreshStatus == .available { // Allows iOS system to schedule background tasks with minimum interval UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum) } ## WorkManager Implementation (Dart/Flutter) ### Initialization ```dart /// Initializes WorkManager static Future<void> initialize() async { await Workmanager().initialize(callbackDispatcher, isInDebugMode: false); print('WorkManagerService: WorkManager initialized'); } ### Task Registration /// Schedules API execution after a specific delay ## Observed Behavior ### Works (Debug/USB Connection) - When running the app via Xcode/USB debugging - Background tasks are scheduled and executed as expected - API calls are made successfully when the app is backgrounded ### Does NOT Work (TestFlight) - When the app is distributed via TestFlight - Background tasks appear to be scheduled (no errors in code) - Tasks are **never executed** when the app is in background - We have tested with: - Background App Refresh enabled in iOS Settings - App used frequently - Device connected to WiFi and charging - Waited for extended periods (hours) ## Possible heart points 1. **Are there any additional configurations required for `BGTaskScheduler` to work in TestFlight/Production builds that are not required for debug builds?** 2. **Is the identifier format correct?** We are using: `br.com.unidas.apprac.ios.workmanager.carrinho_api_task` - Should it match exactly with the task name registered in code? 3. **Are there any known issues with Flutter's `workmanager` plugin and iOS BGTaskScheduler in production environments?** 4. **Is there any way to verify through logs or system diagnostics if the background tasks are being rejected by the system?** 5. **Could there be any conflict between our other background modes (`location`, `remote-notification`) and `processing`?** 6. **Does the Salesforce Marketing Cloud SDK (SFMC) interfere with BGTaskScheduler operations?** ## Additional Context - We have verified that `Background App Refresh` is enabled for our app in iOS Settings - The app has proper entitlements for push notifications and location services - Firebase, SFMC (Salesforce Marketing Cloud), and other SDKs are properly configured - The issue is **only** present in TestFlight builds, not in debug/USB-connected builds ## References - [Apple Documentation - BGTaskScheduler](https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler) - [Apple Documentation - Choosing Background Strategies](https://developer.apple.com/documentation/backgroundtasks/choosing_background_strategies_for_your_app) Thank you
2
0
51
2w
SMAppService getting notified when status changes externally (from System Settings)
Say I want to sync a toggle in my app with SMAppService's .status property. If the status changes from my app I can track it. But if user toggles it from System Settings, I don't see a notification so then the UI in my app is out of date. The status property is not key value observable and there doesn't appear to be a SMAppServiceStatusDidChangeNotification ? I can re-read it every time my app will become active but feels kind of wrong to do it this way.
2
0
79
May ’25
How to safely terminate hanging threads in launched agent context
Hello, In a launched agent, I need to call into a third‑party library that may occasionally hang. At present, these calls are made from a separate thread, but if the thread hangs it cannot be terminated (pthread_cancel/pthread_kill are ineffective). Would Apple recommend isolating this functionality in a separate process that can be force‑terminated if it becomes unresponsive, or is there a preferred approach for handling such cases in launched agents? Can I use the system call fork() in launched agent? Thank you in advance!
2
0
92
Oct ’25
NotificationCenter.notifications(named:) appears to buffer internally and can drop notifications, but is this documented anywhere?
I've experimentally seen that the notifications(named:) API of NotificationCenter appears to buffer observed notifications internally. In local testing it appears to be limited to 8 messages. I've been unable to find any documentation of this fact, and the behavior seems like it could lead to software bugs if code is not expecting notifications to potentially be dropped. Is this behavior expected and documented somewhere? Here is a sample program demonstrating the behavioral difference between the Combine and AsyncSequence-based notification observations: @Test nonisolated func testNotificationRace() async throws { let testName = Notification.Name("TestNotification") let notificationCount = 100 var observedAsyncIDs = [Int]() var observedCombineIDs = [Int]() let subscribe = Task { @MainActor in print("setting up observer...") let token = NotificationCenter.default.publisher(for: testName) .sink { value in let id = value.userInfo?["id"] as! Int observedCombineIDs.append(id) print("🚜 observed note with id: \(id)") } defer { extendLifetime(token) } for await note in NotificationCenter.default.notifications(named: testName) { let id: Int = note.userInfo?["id"] as! Int print("🚰 observed note with id: \(id)") observedAsyncIDs.append(id) if id == notificationCount { break } } } let post = Task { @MainActor in for i in 1...notificationCount { NotificationCenter.default.post( name: testName, object: nil, userInfo: ["id": i] ) } } _ = await (post.value, subscribe.value) #expect(observedAsyncIDs.count == notificationCount) // 🛑 Expectation failed: (observedAsyncIDs.count → 8) == (notificationCount → 100) #expect(observedCombineIDs == Array(1...notificationCount)) print("done") }
2
0
170
2w
Background Task Execution for FDA Class B Medical App Using BLE
Hello Apple Developer Community, I am developing a medical app that is classified as Class B according to FDA regulations. The app connects to a medical device using Bluetooth Low Energy (BLE) to collect critical medical data such as ECG readings. To ensure accurate data collection and maintain the quality of the medical readings, the app needs to wake up every five minutes in the background and perform tasks for approximately 30 seconds. I understand that iOS has strict limitations on background execution to preserve battery and system performance. However, due to the medical nature of the app and the need for periodic data collection, I am seeking guidance on the following: If I can provide documentation that the app is associated with an FDA-approved Class B medical device, would Apple allow more lenient background task execution policies? Are there specific APIs, such as BackgroundTasks, CoreBluetooth, or other recommended strategies, that could help me achieve this behavior reliably? Is there a process to apply for an exception or special consideration for medical apps that require periodic background activity? Any insights or recommendations would be greatly appreciated. Thank you!
2
0
331
Mar ’25
Is there an API to programmatically obtain an XPC Service's execution context?
Hello! I'm writing a System Extension that is an Endpoint Security client. And I want to Deny/Allow executing some XPC Service processes (using the ES_EVENT_TYPE_AUTH_EXEC event) depending on characteristics of a process that starts the XPC Service. For this purpose, I need an API that could allow me to obtain an execution context of the XPC Service process. I can obtain this information using the "sudo launchctl procinfo <pid>" command (e.g. I can use the "domain = pid/3428" part of the output for this purpose). Also, I know that when the xpcproxy process is started, it gets as the arguments a service name and a pid of the process that requests the service so I can grasp the execution context from xpcproxy launching. But are these ways to obtain this info legitimate?
2
0
164
Apr ’25
Push-to-Start Live Activity Background Task Issue After App Termination
Desired Behavior I want the app to be able to handle multiple Push-to-Start notifications even when it is completely terminated. Each Live Activity should: Be successfully displayed upon receiving a Push-to-Start notification. Trigger background tasks to send its update token to the server, regardless of the time interval between notifications. Problem I am facing an issue with iOS Live Activities when using Push-to-Start notifications to trigger Live Activities in an app that has been completely terminated. Here’s the detailed scenario: When the app is completely terminated and I send the first Push-to-Start notification: The Live Activity is successfully displayed. didFinishLaunchingWithOptions` is triggered, and background tasks execute correctly, including sending the update token to the server. When I send consecutive Push-to-Start notifications in quick succession (e.g., within a few seconds or minutes): Both notifications successfully display their respective Live Activities. Background tasks are executed correctly for both notifications. However, when there is a longer interval (e.g., 10 minutes) between two Push-to-Start notifications: The first notification works perfectly—it displays the Live Activity, triggers didFinishLaunchingWithOptions, and executes background tasks. The second notification successfully displays the Live Activity but fails to execute any background tasks, such as sending the update token to the server. My HypothesisI suspect that iOS might impose a restriction where background runtime for Push-to-Start notifications can only be granted once within a certain time frame after the app has been terminated. Any insights into why this issue might be occurring or how to ensure consistent background task execution for multiple Push-to-Start notifications would be greatly appreciated!
2
0
414
Mar ’25
Feature Request: Reason for taskExpiration for BGContinuedProcessingTask
I've tuned my task to be decently resilient, but I found a few issues that caused it to expire regularly. excessive CPU usage -> I'm actually running it behind ReactNative, and I found an issue where I was still updating ReactNative and thus it was keeping it alive the entire time the task was running. Removing this update helped improve stability not updating progress frequently enough ( see https://developer.apple.com/forums/thread/809182?page=1#868247022) My feature request is, would it be possible to get a reason the task was expired in task.expirationHandler? That would be helpful for both the user and for debugging why the task was expired. Thanks!
2
0
99
3d
How to safely maximize concurrent UI rendering
I'm using Swift 6 and tasks to concurrently process multiple PDF files for rendering, and it's working well. But currently I'm manually limiting the number of simultaneous tasks to 2 out of fear that the system might run many tasks concurrently without having enough RAM to do the PDF processing. Testing on a variety of devices, I've tried increasing the task limit and haven't seen any crashes, but I'm quite concerned about the possibility. Any given device might be using a lot of RAM at any moment, and any given PDF might strain resources more than the average PDF. Is there a recommended technique for handling this kind of scenario? Should I not worry about it and just go ahead and start a high number of tasks, trusting that the system won't run too many concurrently and therefore won't run out of RAM?
2
0
266
Mar ’25