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

Processes & Concurrency Resources
General: DevForums subtopic: App & System Services > Processes & Concurrency Processes & concurrency covers a number of different technologies: Background Tasks Resources Concurrency Resources — This includes Swift concurrency. Service Management Resources XPC Resources Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
94
Jul ’25
Control status item and login item from within app
In macOS 26 I noticed there is a section Menu Bar in System Settings which allows to toggle visibility of status items created with NSStatusItem. I'm assuming this is new, since I never noticed it before. Currently my app has a menu item that allows toggling its status item, but now I wonder whether it should always create the status item and let the user control its visibility from System Settings. Theoretically, keeping this option inside the app could lead to confusion if the user has previously disabled the status item in System Settings, then perhaps forgot about it, and then tries to enable it inside the app, but apparently nothing happens because System Settings overrides the app setting. Should I remove the option inside the app? This also makes me think of login items, which can be managed both in System Settings and inside the app via SMAppService. Some users ask why my app doesn't have a launch at login option, and I tell them that System Settings already offers that functionality. Since there is SMAppService I could offer an option inside the app that is kept in sync with System Settings, but I prefer to avoid duplicating functionality, particularly if it's something that is changed once by the user and then rarely (if ever) changed afterwards. But I wonder: why can login items be controlled by an app, and the status item cannot (at least I'm not aware of an API that allows to change the option in System Settings)? If the status item can be overridden in System Settings, why do login items behave differently?
4
0
65
1h
BGContinuedProcessingTask launchHandler invocation
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.
0
0
32
13h
Crash on DispatchQueue.main.sync from isolated thread
I'm troubleshooting a crash I do not understand. I have a queue called DataQueue which never has anything dispatched to it - it's the sample buffer delegate of an AVCaptureVideoDataOutput. It can call DispatchQueue.main.sync to do some work on the main thread. It works fine no matter what we test, but has some crashes in the field that I need to fix. Here's it crashing: AppleCameraDataDelegate.dataQueue 0 libsystem_kernel.dylib 0x7bdc __ulock_wait + 8 1 libdispatch.dylib 0x4a80 _dlock_wait + 52 2 libdispatch.dylib 0x486c _dispatch_thread_event_wait_slow$VARIANT$mp + 52 3 libdispatch.dylib 0x113d8 __DISPATCH_WAIT_FOR_QUEUE__ + 332 4 libdispatch.dylib 0x10ff0 _dispatch_sync_f_slow + 140 The main thread isn't doing something I asked it to, but appears to be busy: Thread 0 libsystem_kernel.dylib 0x71a4 __psynch_cvwait + 8 1 libsystem_pthread.dylib 0x7fd8 _pthread_cond_wait$VARIANT$mp + 1232 2 grpc 0x2cb670 gpr_cv_wait + 131 (sync.cc:131) 3 grpc 0x119688 grpc_core::Executor::ThreadMain(void*) + 225 (executor.cc:225) 4 grpc 0x2e023c grpc_core::(anonymous namespace)::ThreadInternalsPosix::ThreadInternalsPosix(char const*, void (*)(void*), void*, bool*, grpc_core::Thread::Options const&)::'lambda'(void*)::__invoke(void*) + 146 (thd.cc:146) 5 libsystem_pthread.dylib 0x482c _pthread_start + 104 6 libsystem_pthread.dylib 0xcd8 thread_start + 8 Can anyone help me understand why this is a crash?
4
0
93
1d
BGContinuedProcessingTask does not work on the official release of iOS 26
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
4
0
154
2d
Are iPad apps that are closed with the red traffic light prevented from running background tasks?
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?
1
0
48
2d
XPC codesign requirement crashes application
We have an application that sets a code signing requirement on a XPC connection between a File Provider extension and the main application. Only with a specific Developer ID certificate <DEVELOPER_ID_TEAM_IDENTIFIER> that designated requirement is not accepted and the application crashes with EXC_CRASH (SIGABRT) and the stacktrace Thread 1 Crashed:: Dispatch queue: com.apple.root.default-qos 0 libsystem_kernel.dylib 0x19b556388 __pthread_kill + 8 1 libsystem_pthread.dylib 0x19b58f88c pthread_kill + 296 2 libsystem_c.dylib 0x19b498a3c abort + 124 3 libc++abi.dylib 0x19b545384 abort_message + 132 4 libc++abi.dylib 0x19b533cf4 demangling_terminate_handler() + 344 5 libobjc.A.dylib 0x19b1b8dd4 _objc_terminate() + 156 6 libc++abi.dylib 0x19b544698 std::__terminate(void (*)()) + 16 7 libc++abi.dylib 0x19b547c30 __cxxabiv1::failed_throw(__cxxabiv1::__cxa_exception*) + 88 8 libc++abi.dylib 0x19b547bd8 __cxa_throw + 92 9 libobjc.A.dylib 0x19b1aecf8 objc_exception_throw + 448 10 Foundation 0x19d5c3840 -[NSXPCConnection setCodeSigningRequirement:] + 140 11 libxpcfileprovider.dylib 0x301023048 NSXPCConnection.setCodeSigningRequirementFromTeamIdentifier(_:) + 1796 12 libxpcfileprovider.dylib 0x30101dc94 closure #1 in CallbackFileProviderManager.getFileProviderConnection(_:service:completionHandler:interruptionHandler:exportedObject:) + 1936 13 libxpcfileprovider.dylib 0x30101e110 thunk for @escaping @callee_guaranteed @Sendable (@guaranteed NSXPCConnection?, @guaranteed Error?) -> () + 80 14 Foundation 0x19d46c3a4 __72-[NSFileProviderService getFileProviderConnectionWithCompletionHandler:]_block_invoke_2.687 + 284 15 libdispatch.dylib 0x19b3d7b2c _dispatch_call_block_and_release + 32 16 libdispatch.dylib 0x19b3f185c _dispatch_client_callout + 16 17 libdispatch.dylib 0x19b40e490 + 32 18 libdispatch.dylib 0x19b3e9fa4 _dispatch_root_queue_drain + 736 19 libdispatch.dylib 0x19b3ea5d4 _dispatch_worker_thread2 + 156 20 libsystem_pthread.dylib 0x19b58be28 _pthread_wqthread + 232 21 libsystem_pthread.dylib 0x19b58ab74 start_wqthread + 8 The designated codesign requirement on the XPC connection is set to anchor apple generic and certificate leaf[subject.OU] = <DEVELOPER_ID_TEAM_IDENTIFIER>" We have verified the designated code sign requirement to be valid on both the main bundle and the embedded extension using: codesign --verify -v -R '=anchor apple generic and certificate leaf[subject.OU] = "<DEVELOPER_ID_TEAM_IDENTIFIER>"' *.app codesign --verify -v -R '=anchor apple generic and certificate leaf[subject.OU] = "<DEVELOPER_ID_TEAM_IDENTIFIER>"' *.app/Contents/PlugIns/*
2
0
43
3d
Privileged helper without SMJobBless
To establish a privileged helper daemon from a command line app to handle actions requiring root privileges I still use the old way of SMJobBless. But this is deprecated since OSX 10.13 and I want to finally update it to the new way using SMAppService. As I'm concerned with securing it against malicious exploits, do you have a recommended up-to-date implementation in Objective-C establishing a privileged helper and verifying it is only used by my signed app? I've seen the suggestion in the documentation to use SMAppService, but couldn't find a good implementation covering security aspects. My old implementation in brief is as follows: bool runJobBless () { // check if already installed NSFileManager* filemgr = [NSFileManager defaultManager]; if ([filemgr fileExistsAtPath:@"/Library/PrivilegedHelperTools/com.company.Helper"] && [filemgr fileExistsAtPath:@"/Library/LaunchDaemons/com.company.Helper.plist"]) { // check helper version to match the client // ... return true; } // create authorization reference AuthorizationRef authRef; OSStatus status = AuthorizationCreate (NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authRef); if (status != errAuthorizationSuccess) return false; // obtain rights to install privileged helper AuthorizationItem authItem = { kSMRightBlessPrivilegedHelper, 0, NULL, 0 }; AuthorizationRights authRights = { 1, &authItem }; AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights; status = AuthorizationCopyRights (authRef, &authRights, kAuthorizationEmptyEnvironment, flags, NULL); if (status != errAuthorizationSuccess) return false; // SMJobBless does it all: verify helper against app and vice-versa, place and load embedded launchd.plist in /Library/LaunchDaemons, place executable in /Library/PrivilegedHelperTools CFErrorRef cfError; if (!SMJobBless (kSMDomainSystemLaunchd, (CFStringRef)@"com.company.Helper", authRef, &cfError)) { // check helper version to match the client // ... return true; } else { CFBridgingRelease (cfError); return false; } } void connectToHelper () { // connect to helper via XPC NSXPCConnection* c = [[NSXPCConnection alloc] initWithMachServiceName:@"com.company.Helper.mach" options:NSXPCConnectionPrivileged]; c.remoteObjectInterface = [NSXPCInterface interfaceWithProtocol:@protocol (SilentInstallHelperProtocol)]; [c resume]; // call function on helper and wait for completion dispatch_semaphore_t semaphore = dispatch_semaphore_create (0); [[c remoteObjectProxy] callFunction:^() { dispatch_semaphore_signal (semaphore); }]; dispatch_semaphore_wait (semaphore, dispatch_time (DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC)); dispatch_release (semaphore); [c invalidate]; [c release]; }
1
0
49
3d
SMAppService Sample Code seems broken
I abandoned Mac development back around 10.4 when I departed Apple and am playing catch-up, trying to figure out how to register a privileged helper tool that can execute commands as root in the new world order. I am developing on 13.1 and since some of these APIs debuted in 13, I'm wondering if that's ultimately the root of my problem. Starting off with the example code provided here: https://developer.apple.com/documentation/servicemanagement/updating-your-app-package-installer-to-use-the-new-service-management-api Following all build/run instructions in the README to the letter, I've not been successful in getting any part of it to work as documented. When I invoke the register command the test app briefly appears in System Settings for me to enable, but once I slide the switch over, it disappears. Subsequent attempts to invoke the register command are met only with the error message: `Unable to register Error Domain=SMAppServiceErrorDomain Code=1 "Operation not permitted" UserInfo={NSLocalizedFailureReason=Operation not permitted} The app does not re-appear in System Settings on these subsequent invocations. When I invoke the status command the result mysteriously equates to SMAppService.Status.notFound. The plist is in the right place with the right name and it is using the BundleProgram key exactly as supplied in the sample code project. The executable is also in the right place at Contents/Resources/SampleLaunchAgent relative to the app root. The error messaging here is extremely disappointing and I'm not seeing any way for me to dig any further without access to the underlying Objective-C (which the Swift header docs reference almost exclusively, making it fairly clear that this was a... Swift... Port... [Pun intended]).
9
0
140
1w
BGContinuedProcessingTask Notification Error
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!
1
0
62
1w
Stay connected to Medical BLE device in background
I work for a large medical device company. We have a 1st party BLE enabled medical device that must be very battery efficient. To this end, if a connection is lost, the BLE radio is powered down after 60 seconds and will only turn back on when a physical button on the device is pressed. I've been tasked with connecting to the device, staying connected to the device, and being able to retrieve data from the device upon a timed action. For instance, this could include a data read and transmission while they sleep. The key part of this is staying reliably connected for extended periods of time. This is a BYOD setup, and we cannot control power profiles. I would very much appreciate any information, recommendations, and/or insights into solving this problem. Thanks!
1
0
245
1w
[iOS 26 Beta] BGTaskScheduler.supportedResources incorrectly reports no GPU support for BGContinuedProcessingTask on capable hardware
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.
4
0
147
1w
App Terminated with 0x8BADF00D: Main Thread Blocked During Back-to-Back Messaging
Hello, I'm experiencing an issue with my app where it's being terminated by the system with a watchdog violation during back-to-back messaging operations. I've analyzed the crash logs but would appreciate additional insights on optimizing my approach. I'd appreciate any insights on how to resolve this problem. Crash Details: Exception Type: EXC_CRASH (SIGKILL) Termination Reason: FRONTBOARD with code 0x8BADF00D Error: "scene-update watchdog transgression: app exhausted real time allowance of 10.00 seconds" Reproduction Steps: User A initiates back-to-back messages to other User User A's UI becomes unresponsive and eventually the app crashes. Stack Trace Analysis: The crash occurs on the main thread, which appears to be blocked waiting for a condition in the keyboard handling system. The thread is stuck in [UIKeyboardTaskQueue _lockWhenReadyForMainThread] and related methods, suggesting an issue with keyboard-related operations during the messaging process. Crash Tag Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: FRONTBOARD 2343432205 <RBSTerminateContext| domain:10 code:0x8BADF00D explanation:scene-update watchdog transgression: app<com.msikodiak.eptt(AD934F8A-DF57-4B75-BE73-8CF1A9A8F856)>:301 exhausted real (wall clock) time allowance of 10.00 seconds ProcessVisibility: Foreground ProcessState: Running WatchdogEvent: scene-update WatchdogVisibility: Background WatchdogCPUStatistics: ( "Elapsed total CPU time (seconds): 6.390 (user 3.640, system 2.750), 11% CPU", "Elapsed application CPU time (seconds): 0.020, 0% CPU" ) ThermalInfo: ( "Thermal Level: 0", "Thermal State: nominal" ) reportType:CrashLog maxTerminationResistance:Interactive> Triggered by Thread: 0 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libsystem_kernel.dylib 0x1e773d438 __psynch_cvwait + 8 1 libsystem_pthread.dylib 0x2210bc328 _pthread_cond_wait + 1028 2 Foundation 0x1957d8a64 -[NSCondition waitUntilDate:] + 132 3 Foundation 0x1957d8888 -[NSConditionLock lockWhenCondition:beforeDate:] + 80 4 UIKitCore 0x1998f1238 -[UIKeyboardTaskQueue _lockWhenReadyForMainThread] + 456 5 UIKitCore 0x19a3d775c __59-[UIKeyboardImpl updateAutocorrectPrompt:executionContext:]_block_invoke_9 + 28 6 UIKitCore 0x19986b084 -[UIKeyboardTaskQueue lockWhenReadyForMainThread] + 168 7 UIKitCore 0x19a3f2994 -[UIKeyboardTaskQueue waitUntilTaskIsFinished:] + 148 8 UIKitCore 0x19a3f2ac4 -[UIKeyboardTaskQueue performSingleTask:breadcrumb:] + 132 9 UIKitCore 0x199e2f7e4 -[_UIKeyboardStateManager updateForChangedSelection] + 144 10 UIKitCore 0x199e24200 -[_UIKeyboardStateManager invalidateTextEntryContextForTextInput:] + 92 11 WebKit 0x1ad52fa54 WebKit::PageClientImpl::didProgrammaticallyClearFocusedElement(WebCore::ElementContext&&) + 40 12 WebKit 0x1ad55adcc WebKit::WebPageProxy::didProgrammaticallyClearFocusedElement(WebCore::ElementContext&&) + 136 13 WebKit 0x1acec74e8 WebKit::WebPageProxy::didReceiveMessage(IPC::Connection&, IPC::Decoder&) + 18604 14 WebKit 0x1acd21184 IPC::MessageReceiverMap::dispatchMessage(IPC::Connection&, IPC::Decoder&) + 236 15 WebKit 0x1ace449b8 WebKit::WebProcessProxy::dispatchMessage(IPC::Connection&, IPC::Decoder&) + 40 16 WebKit 0x1ace44228 WebKit::WebProcessProxy::didReceiveMessage(IPC::Connection&, IPC::Decoder&) + 1764 17 WebKit 0x1acd1e904 IPC::Connection::dispatchMessage(***::UniqueRef<IPC::Decoder>) + 268 18 WebKit 0x1acd1e478 IPC::Connection::dispatchIncomingMessages() + 576 19 JavaScriptCore 0x1ae386b8c ***::RunLoop::performWork() + 524 20 JavaScriptCore 0x1ae386960 ***::RunLoop::performWork(void*) + 36 21 CoreFoundation 0x196badce4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 28 22 CoreFoundation 0x196badc78 __CFRunLoopDoSource0 + 172 23 CoreFoundation 0x196bac9fc __CFRunLoopDoSources0 + 232 24 CoreFoundation 0x196babc3c __CFRunLoopRun + 840 25 CoreFoundation 0x196bd0700 CFRunLoopRunSpecific + 572 26 GraphicsServices 0x1e3711190 GSEventRunModal + 168 27 UIKitCore 0x1997ee240 -[UIApplication _run] + 816 28 UIKitCore 0x1997ec470 UIApplicationMain + 336 29 Telstra PTT 0x1004d30c8 main + 56 30 dyld 0x1bd5d3ad8 start + 5964
3
0
170
1w
LLDB Cannot Load ODBC Driver Due to Sandbox Restrictions - How to Debug
I'm developing a macOS console application that uses ODBC to connect to PostgreSQL. The application works fine when run normally, but fails to load the ODBC driver when debugging with LLDB(under root works fine as well). Error Details When running the application through LLDB, I get this sandbox denial in the system log (via log stream): Error 0x0 0 0 kernel: (Sandbox) Sandbox: logd_helper(587) deny(1) file-read-data /opt/homebrew/lib/psqlodbcw.so The application cannot access the PostgreSQL ODBC driver located at /opt/homebrew/lib/psqlodbcw.so(also tried copy to /usr/local/lib/...). Environment macOS Version: Latest Sequoia LLDB: Using LLDB from Xcode 16.3 (/Applications/Xcode16.3.app/Contents/Developer/usr/bin/lldb) ODBC Driver: PostgreSQL ODBC driver installed via Homebrew Code Signing: Application is signed with Apple Development certificate What is the recommended approach for debugging applications that need to load dynamic libraries? Are there specific entitlements or configurations that would allow LLDB to access ODBC drivers during debugging sessions? Any guidance would be greatly appreciated. Thank you for any assistance!
1
0
154
1w
Background App Refresh
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 { }
22
0
334
1w
Helper app is sandboxed (entitlement + runtime check), but `URLsForDirectory:` returns user home (`/Users//`) instead of container path — why?
Problem summary I have a macOS helper app that is launched from a sandboxed main app. The helper: has com.apple.security.app-sandbox = true and com.apple.security.inherit = true in its entitlements, is signed and embedded inside the main app bundle (placed next to the main executable in Contents/MacOS), reports entitlement_check = 1 (code signature contains sandbox entitlement, implemented via SecStaticCode… check), sandbox_check(getpid(), NULL, 0) returns 1 (runtime sandbox enforcement present), APP_SANDBOX_CONTAINER_ID environment variable is not present (0). Despite that, Cocoa APIs return non-container home paths: NSHomeDirectory() returns /Users/&lt;me&gt;/ (the real home). [[NSFileManager defaultManager] URLsForDirectory:inDomains:] and URLForDirectory:inDomain:appropriateForURL:create:error: return paths rooted at /Users/&lt;me&gt;/ (not under ~/Library/Containers/&lt;app_id&gt;/Data/...) — i.e. they look like non-sandboxed locations. However, one important exception: URLForDirectory:... for NSItemReplacementDirectory (temporary/replacement items) does return a path under the helper's container (example: ~/Library/Containers/&lt;app_id&gt;/Data/tmp/TemporaryItems/NSIRD_&lt;helper_name&gt;_hfc1bZ). This proves the sandbox is active for some FileManager APIs, yet standard directory lookups (Application Support, Documents, Caches, and NSHomeDirectory()) are not being redirected to the container. What I expect The helper (which inherits the sandbox and is clearly sandboxed) should get container-scoped paths from Cocoa’s FileManager APIs (Application Support, Documents, Caches), i.e. paths under the helper’s container: /Users/&lt;me&gt;/Library/Containers/&lt;app_id&gt;/Data/.... What I tried / diagnostics already gathered Entitlements &amp; code signature codesign -d --entitlements :- /path/to/Helper.app/Contents/MacOS/Helper # shows com.apple.security.app-sandbox = true and com.apple.security.inherit = true Runtime checks (Objective-C++ inside helper): extern "C" int sandbox_check(pid_t pid, const char *op, int flags); NSLog(@"entitlement_check = %d", entitlement_check()); // SecStaticCode check NSLog(@"env_variable_check = %d", (getenv("APP_SANDBOX_CONTAINER_ID") != NULL)); NSLog(@"runtime_sandbox_check = %d", sandbox_check(getpid(), nullptr, 0)); NSLog(@"NSHomeDirectory = %s", NSHomeDirectory()); NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask]; NSLog(@"URLsForDirectory: %@", urls); Observed output: entitlement_check = 1 env_variable_check = 0 runtime_sandbox_check = 1 NSHomeDirectory = /Users/&lt;me&gt; URLsForDirectory: ( "file:///Users/&lt;me&gt;/Library/Application%20Support/..." ) Temporary/replacement directory (evidence sandbox active for some APIs): NSURL *tmpReplacement = [[NSFileManager defaultManager] URLForDirectory:NSItemReplacementDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&amp;err]; NSLog(@"NSItemReplacementDirectory: %@", tmpReplacement.path); Observed output (example): /Users/&lt;me&gt;/Library/Containers/&lt;app_id&gt;/Data/tmp/TemporaryItems/NSIRD_&lt;helper_name&gt;_hfc1bZ Other facts Calls to NSHomeDirectory() and URLsForDirectory: are made after main() to avoid "too early" initialization problems. Helper is placed in Contents/MacOS (not Contents/Library/LoginItems). Helper is a non-GUI helper binary launched by the main app (not an XPC service). macOS version: Sequoia 15.6 Questions Why do NSHomeDirectory() and URLsForDirectory: return the real /Users/&lt;me&gt;/... paths in a helper process that is clearly sandboxed (entitlement + runtime enforcement), while NSItemReplacementDirectory returns a container-scoped temporary path? Is this behavior related to how the helper is packaged or launched (e.g., placement in Contents/MacOS vs Contents/Library/LoginItems, or whether it is launched with posix_spawn/fork+exec vs other APIs)? Are there additional entitlements or packaging rules required for a helper that inherits sandbox to have Cocoa directory APIs redirected to the container (for Application Support, Documents, Caches)? *Thanks in advance — I can add any requested logs
6
0
86
2w
How is BGContinuedProcessingTask intended to be used?
Hello, I'm trying to adopt the new BGContinuedProcessingTask API, but I'm having a little trouble imagining how the API authors intended it be used. I saw the WWDC talk, but it lacked higher-level details about how to integrate this API, and I can't find a sample project. I notice that we can list wildcard background task identifiers in our Info.plist files now, and it appears this is to be used with continued tasks - a user might start one video encoding, then while it is ongoing, enqueue another one from the same app, and these tasks would have identifiers such as "MyApp.VideoEncoding.ABCD" and "MyApp.VideoEncoding.EFGH" to distinguish them. When it comes to implementing this, is the expectation that we: a) Register a single handler for the wildcard pattern, which then figures out how to fulfil each request from the identifier of the passed-in task instance? Or b) Register a unique handler for each instance of the wildcard pattern? Since you can't unregister handlers, any resources captured by the handler would be leaked, so you'd need to make sure you only register immediately before submission - in other words register + submit should always be called as a pair. Of course, I'd like to design my application to use this API as the authors intended it be used, but I'm just not entirely sure what that is. When I try to register a single handler for a wildcard pattern, the system rejects it at runtime (while allowing registrations for each instance of the pattern, indicating that at least my Info.plist is configured correctly). That points towards option B. If it is option B, it's potentially worth calling that out in documentation - or even better, perhaps introduce a new call just for BGContinuedProcessingTask instead of the separate register + submit calls? Thanks for your insight. K Aside: Also, it would be really nice if the handler closure would be async. Currently if you need to await on something, you need to launch an unstructured Task, but that causes issues since BGContinuedProcessingTask is not Sendable, so you can't pass it in to that Task to do things like update the title or mark the BGTask as complete.
9
0
205
2w
Electron app with Express + Python child processes not running in macOS production build
Hi all, I’ve built an Electron application that uses two child processes: An Express.js server A Python executable (packaged .exe/binary) During the development phase, everything works fine — the Electron app launches, both child processes start, and the app functions as expected. But when I create a production build for macOS, the child processes don’t run. Here’s a simplified snippet from my electron.mjs: import { app, BrowserWindow } from "electron"; import { spawn } from "child_process"; import path from "path"; let mainWindow; const createWindow = () =&gt; { mainWindow = new BrowserWindow({ width: 1200, height: 800, webPreferences: { nodeIntegration: true, }, }); mainWindow.loadFile("index.html"); // Start Express server const serverPath = path.join(process.resourcesPath, "app.asar.unpacked", "server", "index.js"); const serverProcess = spawn(process.execPath, [serverPath], { stdio: "inherit", }); // Start Python process const pythonPath = path.join(process.resourcesPath, "app.asar.unpacked", "python", "myapp"); const pythonProcess = spawn(pythonPath, [], { stdio: "inherit", }); serverProcess.on("error", (err) =&gt; console.error("Server process error:", err)); pythonProcess.on("error", (err) =&gt; console.error("Python process error:", err)); }; app.whenReady().then(createWindow); I’ve already done the following: Configured package.json with the right build settings Set up extraResources / asarUnpack to include the server and Python files Verified both child processes work standalone Questions: What’s the correct way to package and spawn these child processes for macOS production builds? Do I need to move them into a specific location (like Contents/Resources/app.asar.unpacked) and reference them differently? Is there a more reliable pattern for handling Express + Python child processes inside an Electron app bundle? Any insights or working examples would be really appreciated!
2
0
39
2w
Mac: Best way to distinguish native app process and script process spawned from executable (e.g. python node) through process_id
I'm working on a Mac app that receives a process ID via NSXPCConnection, and I'm trying to figure out the best way to determine whether that process is a native macOS app like Safari—with bundles and all—or just a script launched by something like Node or Python. The executable is signed with a Team ID using codesign. I was thinking about getting the executable's path as one way to handle it, but I’m wondering if there’s a more reliable method than relying on the folder structure.
1
0
154
3w