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

Spawning electron app from deamon process
Hi all, Our company has an application that runs on several machines, this app is launched via a deamon that keeps it alive. One of the feature of this app, is to start a headless electron application to run some tests. When spawning this electron application with the new arm64 OS, we are getting this issue: Silent Test Agent Worker exited with code: 133 [ERROR] [75873:0205/135842.347044:ERROR:mach_port_rendezvous.cc(384)] bootstrap_look_up com.hivestreaming.silenttestagent.MachPortRendezvousServer.1: Permission denied (1100) [ERROR] [75873:0205/135842.347417:ERROR:shared_memory_switch.cc(237)] No rendezvous client, terminating process (parent died?) [ERROR] [75872:0205/135842.347634:ERROR:mach_port_rendezvous.cc(384)] bootstrap_look_up com.hivestreaming.silenttestagent.MachPortRendezvousServer.1: Permission denied (1100) [ERROR] [75872:0205/135842.347976:ERROR:shared_memory_switch.cc(237)] No rendezvous client, terminating process (parent died?) Both application (main app and electron one) are signed and notarized, but it seems that there is some other permission issue. If we run the electron application manually, all runs as expected. I added the crash report as attachment CrashReport.log
2
0
452
Feb ’25
Termination due to Exceed Port Limit
Hi, I have received the following report after app termination. I have researched online but cannot determine the root cause. Any tips or ideas would help please. Could it be Location Services, UserNotification Services, or Network Requests? Thank you, Brendan Translated Report (Full Report Below) Incident Identifier: 6CD59A17-15B1-4F4E-AE84-0286F22893A4 CrashReporter Key: 3d12fb7359053239708afd24c7eed0267a9cc601 Hardware Model: iPhone13,3 Process: AnchorNet3 [5605] Path: /private/var/containers/Bundle/Application/5EA7F893-D562-45B8-8995-5EAB15F85A7E/AnchorNet3.app/AnchorNet3 Identifier: com.sailsecrets.AnchorNet3 Version: 3.17 (3.17) Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: com.sailsecrets.AnchorNet3 [1443] Date/Time: 2025-02-06 00:12:03.6136 +0100 Launch Time: 2025-02-05 22:11:19.4220 +0100 OS Version: iPhone OS 18.2 (22C5131e) Release Type: Beta Baseband Version: 5.20.03 Report Version: 104 Exception Type: EXC_RESOURCE (SIGKILL) Exception Codes: 0x0000000000020000, 0x0000000000000000 Termination Reason: PORT_SPACE 14123288431434006528 (Limit 131072 ports) Exceeded system-wide per-process Port Limit Triggered by Thread: 3 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0: 0 libsystem_kernel.dylib 0x1e27414e4 kevent_id + 8 1 libdispatch.dylib 0x198f51b40 _dispatch_kq_poll + 228 2 libdispatch.dylib 0x198f51080 _dispatch_event_loop_poke + 340 3 QuartzCore 0x192d4631c CA::Context::commit_transaction(CA::Transaction*, double, double*) + 17164 4 QuartzCore 0x192cb8d58 CA::Transaction::commit() + 648 5 QuartzCore 0x192cb8764 CA::Transaction::flush_as_runloop_observer(bool) + 88 6 UIKitCore 0x193a3fd14 _UIApplicationFlushCATransaction + 52 7 UIKitCore 0x193a3d1e0 __setupUpdateSequence_block_invoke_2 + 332 8 UIKitCore 0x193a3d054 UIUpdateSequenceRun + 84 9 UIKitCore 0x193a3f984 schedulerStepScheduledMainSection + 172 10 UIKitCore 0x193a3d5a0 runloopSourceCallback + 92 11 CoreFoundation 0x1911f1f3c CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 28 12 CoreFoundation 0x1911f1ed0 __CFRunLoopDoSource0 + 176 13 CoreFoundation 0x1911f4b30 __CFRunLoopDoSources0 + 244 14 CoreFoundation 0x1911f3d2c __CFRunLoopRun + 840 15 CoreFoundation 0x191246274 CFRunLoopRunSpecific + 588 16 GraphicsServices 0x1de34d4c0 GSEventRunModal + 164 17 UIKitCore 0x193d8f480 -[UIApplication run] + 816 18 UIKitCore 0x1939b5410 UIApplicationMain + 340 19 SwiftUI 0x195b43e30 closure #1 in KitRendererCommon(:) + 168 20 SwiftUI 0x195b43d60 runApp(:) + 100 21 SwiftUI 0x195b43c44 static App.main() + 180 22 AnchorNet3.debug.dylib 0x1025e97bc static MainApp.$main() + 40 23 AnchorNet3.debug.dylib 0x1025eaacc __debug_main_executable_dylib_entry_point + 12 24 dyld 0x1b7352de8 start + 2724 Thread 1 name: com.apple.CoreMotion.MotionThread Thread 1: 0 libsystem_kernel.dylib 0x1e2741788 mach_msg2_trap + 8 1 libsystem_kernel.dylib 0x1e2744e98 mach_msg2_internal + 80 2 libsystem_kernel.dylib 0x1e2744db0 mach_msg_overwrite + 424 3 libsystem_kernel.dylib 0x1e2744bfc mach_msg + 24 4 CoreFoundation 0x1911f47f4 __CFRunLoopServiceMachPort + 160 5 CoreFoundation 0x1911f3ea0 __CFRunLoopRun + 1212 6 CoreFoundation 0x191246274 CFRunLoopRunSpecific + 588 7 CoreFoundation 0x191259814 CFRunLoopRun + 64 8 CoreMotion 0x19e89cc5c 0x19e88d000 + 64604 9 libsystem_pthread.dylib 0x21bcfb7d0 _pthread_start + 136 10 libsystem_pthread.dylib 0x21bcfb480 thread_start + 8 Thread 2 name: com.apple.uikit.eventfetch-thread Thread 2: 0 libsystem_kernel.dylib 0x1e2741788 mach_msg2_trap + 8 1 libsystem_kernel.dylib 0x1e2744e98 mach_msg2_internal + 80 2 libsystem_kernel.dylib 0x1e2744db0 mach_msg_overwrite + 424 3 libsystem_kernel.dylib 0x1e2744bfc mach_msg + 24 4 CoreFoundation 0x1911f47f4 __CFRunLoopServiceMachPort + 160 5 CoreFoundation 0x1911f3ea0 __CFRunLoopRun + 1212 6 CoreFoundation 0x191246274 CFRunLoopRunSpecific + 588 7 Foundation 0x18fdc8338 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212 8 Foundation 0x18ff24e24 -[NSRunLoop(NSRunLoop) runUntilDate:] + 64 9 UIKitCore 0x193e22a74 -[UIEventFetcher threadMain] + 420 10 Foundation 0x18feb4194 NSThread__start + 724 11 libsystem_pthread.dylib 0x21bcfb7d0 _pthread_start + 136 12 libsystem_pthread.dylib 0x21bcfb480 thread_start + 8 Thread 3 name: com.apple.SwiftUI.AsyncRenderer Thread 3 Crashed: 0 libsystem_kernel.dylib 0x1e274162c _kernelrpc_mach_port_allocate_trap + 8 1 libsystem_kernel.dylib 0x1e2748478 mach_port_allocate + 36 2 QuartzCore 0x192d4552c CA::Context::commit_transaction(CA::Transaction*, double, double*) + 13596 3 QuartzCore 0x192cb8d58 CA::Transaction::commit() + 648 4 QuartzCore 0x192cb8764 CA::Transaction::flush_as_runloop_observer(bool) + 88 5 CoreFoundation 0x19119f894 CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 36 6 CoreFoundation 0x19119f3e8 __CFRunLoopDoObservers + 552 7 CoreFoundation 0x1912462c0 CFRunLoopRunSpecific + 664 8 Foundation 0x18fdc8338 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212 9 Foundation 0x18fdc4500 -[NSRunLoop(NSRunLoop) run] + 64 10 SwiftUI 0x195c276d8 specialized static DisplayLink.asyncThread(arg:) + 792 11 SwiftUI 0x195c273a8 @objc static DisplayLink.asyncThread(arg:) + 72 <>
11
0
520
Feb ’25
Why is xpc_connection_set_peer_code_signing_requirement() closing the connection instead of returning XPC_ERROR_PEER_CODE_SIGNING_REQUIREMENT?
I'm using libxpc in a C server and Swift client. I set up a code-signing requirement in the server using xpc_connection_set_peer_code_signing_requirement(). However, when the client doesn't meet the requirement, the server just closes the connection, and I get XPC_ERROR_CONNECTION_INTERRUPTED on the client side instead of XPC_ERROR_PEER_CODE_SIGNING_REQUIREMENT, making debugging harder. What I want: To receive XPC_ERROR_PEER_CODE_SIGNING_REQUIREMENT on the client when code-signing fails, for better debugging. What I’ve tried: Using xpc_connection_set_peer_code_signing_requirement(), but it causes the connection to be dropped immediately. Questions: Why does the server close the connection without sending the expected error? How can I receive the correct error on the client side? Are there any other methods for debugging code-signing failures with libxpc? Thanks for any insights!
1
0
431
Feb ’25
Combine delay & switchToLatest publisher don't emit value sometimes
Hello, I recently implemented a conditional debounce publisher using Swift's Combine. If a string with a length less than 2 is passed, the event is sent downstream immediately without delay. If a string with a length of 2 or more is passed, the event is emitted downstream with a 0.2-second delay. While writing test logic related to this, I noticed a strange phenomenon: sometimes the publisher, which should emit events with a 0.2-second delay, does not emit an event. The test code below should have all indices from 1 to 100 in the array, but sometimes some indices are missing, causing the assertion to fail. Even after observing completion, cancel, and output events through handleEvents, I couldn't find any cause. Am I using Combine incorrectly, or is there a bug in Combine? I would appreciate it if you could let me know. import Foundation import Combine var cancellables: Set<AnyCancellable> = [] @MainActor func text(index: Int, completion: @escaping () -> Void) { let subject = PassthroughSubject<String, Never>() let textToSent = "textToSent" subject .map { text in if text.count >= 2 { return Just<String>(text) .delay(for: .seconds(0.2), scheduler: RunLoop.main) .eraseToAnyPublisher() } else { return Just<String>(text) .eraseToAnyPublisher() } } .switchToLatest() .sink { if $0.count >= 2 { completion() } }.store(in: &cancellables) for i in 0..<textToSent.count { let stringIndex = textToSent.index(textToSent.startIndex, offsetBy: i) let stringToSent = String(textToSent[textToSent.startIndex...stringIndex]) subject.send(stringToSent) } } var array = [Int]() for i in 1...100 { text(index: i) { array.append(i) } } DispatchQueue.main.asyncAfter(deadline: .now() + 5) { for i in 1...100 { assert(array.contains(i)) } } RunLoop.main.run(until: .now + 10)
0
0
356
Feb ’25
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
418
Feb ’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
321
Feb ’25
Issue with launchd Job Not Running – "Bootstrap failed: 5: Input/output error"
Purpose I want to use launchd to run a shell script asynchronously every minute, but I'm encountering an issue where the job does not run, and I receive the error "Bootstrap failed: 5: Input/output error". I need help identifying the cause of this issue and how to configure launchd correctly. What I've done Created the shell script (test_ls_save.sh) The script is designed to list the contents of the desktop and save the output to a specified directory. #!/bin/bash DATE=$(date +%Y-%m-%d_%H-%M-%S) SAVE_DIR=/Users/test/Desktop/personal/log_gather FILE_NAME="ls_output_$DATE.log" ls ~/Desktop &gt; "$SAVE_DIR/$FILE_NAME" echo "ls output saved to $SAVE_DIR/$FILE_NAME" File permissions (ls -l output): -rwxr-xr-x 1 test staff 1234 Feb 17 10:00 /Users/test/Desktop/personal/log_gather/exec/test_ls_save.sh Created the launchd plist file (com.test.logTest.plist) The plist file is configured to execute the shell script every minute. &lt;key&gt;Label&lt;/key&gt; &lt;string&gt;com.test.logTest&lt;/string&gt; &lt;key&gt;ProgramArguments&lt;/key&gt; &lt;array&gt; &lt;string&gt;/bin/bash&lt;/string&gt; &lt;string&gt;-c&lt;/string&gt; /Users/test/Desktop/personal/log_gather/exec/test_ls_save.sh &lt;/array&gt; &lt;key&gt;StartInterval&lt;/key&gt; &lt;integer&gt;60&lt;/integer&gt; &lt;!-- Run every minute --&gt; File permissions (ls -l output): -rwxr-xr-x 1 test staff 512 Feb 17 10:00 /Users/test/Library/LaunchAgents/com.test.logTest.plist Ran the job with launchctl I used the following command to load the plist file into launchd: sudo launchctl bootstrap gui/$(id -u) /Users/test/Library/LaunchAgents/com.test.logTest.plist pc spec MacBook Pro Apple M1 16 GB RAM macOS 15.3 (Build 24D60) what I know The configuration has been set, but the launchd job is not running every minute as expected. I don't believe there is a mistake with the path. When I check the job using launchctl list, the job does not appear in the list. I don't know where the error log files are supposed to be. I checked /var/log/system.log, but there are no error logs. The .sh file runs fine by itself, but it cannot be executed via launchctl. Want to ask What could be the cause of the launchd job not running as expected? Also, is there a way to check where the logs are being output? If there is an error in the plist file configuration, which part should be modified? Specifically, what improvements should be made regarding environment variables and path settings? If my information is not enough, please tell me what is not enough!
1
0
498
Feb ’25
My system daemons are not getting launched in MacOS 15x post reboot
When I install my application, it installs fine and everything works alongwith all the system level daemons but when I reboot the system, none of my daemons are getting launched and this happens only on MacOS 15x, on older version it is working fine. In the system logs, I see that my daemons have been detected as legacy daemons by backgroundtaskmanagementd with Disposition [enabled, allowed, visible, notified] 2025-01-13 21:17:04.919128+0530 0x60e Default 0x0 205 0 backgroundtaskmanagementd: [com.apple.backgroundtaskmanagement:main] Type: legacy daemon (0x10010) 2025-01-13 21:17:04.919128+0530 0x60e Default 0x0 205 0 backgroundtaskmanagementd: [com.apple.backgroundtaskmanagement:main] Flags: [ legacy ] (0x1) 2025-01-13 21:17:04.919129+0530 0x60e Default 0x0 205 0 backgroundtaskmanagementd: [com.apple.backgroundtaskmanagement:main] Disposition: [enabled, allowed, visible, notified] (0xb) But later, it backgroundtaskmanagementd decides to disallow it. 2025-01-13 21:17:05.013202+0530 0x32d Default 0x4d6 89 0 smd: (BackgroundTaskManagement) [com.apple.backgroundtaskmanagement:main] getEffectiveDisposition: disposition=[enabled, disallowed, visible, notified], have LWCR=true 2025-01-13 21:17:05.013214+0530 0x32d Error 0x0 89 0 smd: [com.apple.xpc.smd:all] Legacy job is not allowed to launch: &lt;private&gt; status: 2 Is there anything changed in latest Mac OS which is causing this issue? Also what does this status 2 means. Can someone please help with this error? The plist has is true
3
0
298
Feb ’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
263
Feb ’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
387
Feb ’25
Proper initialization - views, dependencies, laoder and viewcontroller
So i am pretty new to Xcode, but i have been using Python and other language for some while. But I am quite new to the game of view and view control. So it may be that i have over complicated this a bit - and it may be that I have some wrong understanding of the dependencies and appcontroller (that i thought would be a good idea). So here we have a main file we call it app.swift, we have a startupmanager.swift, a appcoordinator and a dependeciescontainer. But it may be that this is either a overkill - or that I am doing it wrong. So my thought was that i had a dependeciecontainer, a appcoordinator for the views and a startupmanager that controll the initialized fetching. I have controlled the memory when i run it - checking if it is higher, lower eg - but it was first when i did my 2 days profile i saw a lot of new errors, like this: Fikser(7291,0x204e516c0) malloc: xzm: failed to initialize deferred reclamation buffer (46). and i also get macro errors, probably from the @Query in my feedview. So my thought was that a depencecie manager and a startupmanager was a good idea together with a app coordinator. But maybe I am wrong - maybe this is not a good idea? Or maybe I am doing some things twice? I have added a lot of prints and debugs for checking. But it seems that it starts off to heavy? import SwiftUI import Combine @MainActor class AppCoordinator: ObservableObject { @Published var isLoggedIn: Bool = false private var authManager: AuthenticationManager = .shared private var cancellables = Set<AnyCancellable>() private let startupManager: StartupManager private let container: DependencyContainer @Published var path = NavigationPath() enum Screen: Hashable, Identifiable { case profile case activeJobs case offers case message var id: Self { self } } init(container: DependencyContainer) { self.container = container self.startupManager = container.makeStartupManager() setupObserving() startupManager.start() print("AppCoordinator initialized!") } private func setupObserving() { authManager.$isAuthenticated .receive(on: RunLoop.main) .sink { [weak self] isAuthenticated in self?.isLoggedIn = isAuthenticated } .store(in: &cancellables) } func userDidLogout() { authManager.logout() path.removeLast(path.count) } func showProfile() { path.append(Screen.profile) } func showActiveJobs() { path.append(Screen.activeJobs) } func showOffers() { path.append(Screen.offers) } func showMessage() { path.append(Screen.message) } @ViewBuilder func viewForDestination(_ destination: Screen) -> some View { switch destination { case .profile: ProfileView() case .activeJobs: ActiveJobsView() case .offers: OffersView() case .message: ChatView() } } @ViewBuilder func viewForJob(_ job: Job) -> some View { PostDetailView( job: job, jobUserDetailsRepository: container.makeJobUserDetailsRepository() ) } @ViewBuilder func viewForProfileSubview(_ destination: ProfileView.ProfileSubviews) -> some View { switch destination{ case .personalSettings: PersonalSettingView() case .historicData: HistoricDataView() case .transactions: TransactionView() case .helpCenter: HelpcenterView() case .helpContract: HelpContractView() } } enum HomeBarDestinations: Hashable, Identifiable { case postJob case jobPosting var id: Self { self } } @ViewBuilder func viewForHomeBar(_ destination: HomeBarView.HomeBarDestinations) -> some View { switch destination { case .postJob: PostJobView() } } } import Apollo import FikserAPI import SwiftData class DependencyContainer { static var shared: DependencyContainer! private let modelContainer: ModelContainer static func initialize(with modelContainer: ModelContainer) { shared = DependencyContainer(modelContainer: modelContainer) } private init(modelContainer: ModelContainer) { self.modelContainer = modelContainer print("DependencyContainer being initialized at ") } @MainActor private lazy var userData: UserData = { return UserData(apollo: Network.shared.apollo) }() @MainActor private lazy var userDetailsRepository: UserDetailsRepository = { return UserDetailsRepository(userData: makeUserData()) }() @MainActor private lazy var jobData: JobData = { return JobData(apollo: Network.shared.apollo) }() @MainActor private lazy var jobRepository: JobRepository = { return JobRepository(jobData: makeJobData(), modelContainer: modelContainer) }() @MainActor func makeUserData() -> UserData { return userData } @MainActor func makeUserDetailsRepository() -> UserDetailsRepository { return userDetailsRepository } @MainActor func makeStartupManager() -> StartupManager { return StartupManager( userDetailsRepository: makeUserDetailsRepository(), jobRepository: makeJobRepository(), authManager: AuthenticationManager.shared, lastUpdateRepository: makeLastUpdateRepository() ) } @MainActor func makeJobData() -> JobData { return jobData } @MainActor func makeJobRepository() -> any JobRepositoryProtocol { return jobRepository } @MainActor private lazy var jobUserData: JobUserData = { return JobUserData(apollo: Network.shared.apollo) }() @MainActor private lazy var jobUserDetailsRepository: JobUserDetailsRepository = { return JobUserDetailsRepository(jobUserData: makeJobUserData()) }() @MainActor func makeJobUserData() -> JobUserData { return jobUserData } @MainActor func makeJobUserDetailsRepository() -> JobUserDetailsRepository { return jobUserDetailsRepository } @MainActor private lazy var lastUpdateData: LastUpdateData = { return LastUpdateData(apollo: Network.shared.apollo) }() @MainActor private lazy var lastUpdateRepository: LastUpdateRepository = { return LastUpdateRepository(lastUpdateData: makeLastUpdateData()) }() @MainActor func makeLastUpdateData() -> LastUpdateData { return lastUpdateData } @MainActor func makeLastUpdateRepository() -> LastUpdateRepository { return lastUpdateRepository } }```
1
0
303
Feb ’25
BGTaskScheduler crashes on iOS 18.4
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
33
8
3.3k
Feb ’25
[MacOS] Accessing underlying pthread or mach thread of NSThread
Is the title possible ? I tried [[thread valueForKey:@"_private"] valueForKey:@"tid"] but the tid was not kvc compliant. private apis are alright because this is just for testing remote process thread creation. I already have a working method but it has hardcoded assembly so you can't do anything else. this question is mainly for Quinn (figured he may know something about this)
2
0
291
Feb ’25
Can we create a bundled non-interactive macOS application which uses CFRunLoop only(instead of using NSApplicationMain to run NSRunLoop)?
I am developing a macOS non-interactive macOS application which does not show any ui. i want to block main thread and do all the work on worker thread . Once done with work in worker thread, want to unblock main thread by exiting event loop to terminate application. Because i dont want to show any UI or use any Foundation/Cocoa functionality, i am thinking of using CFRunLoop to block main thread from exiting until i finish my work in worker thread. When i tried this in a project, I am able to finish work in worker thread after block main thread using CFRunLoop. I also want this application to be a bundled application, which can be launched by double clicking on application bundle . But when i tried it in my xcode project by launching it using double clicking on application bundle, application keeps on toggling/bouncing in the dock menu with a status "Not responding". Although i am able to complete my work in worker thread. import Foundation let runLoop = CFRunLoopGetCurrent() func workerTask() { DispatchQueue.global().async { print("do its work") sleep(5) // do some work print("calling exit event loop") CFRunLoopStop(runLoop) print ("unblocking main thread") } } workerTask () // blocking main thread print ("blocked main thread") CFRunLoopRun() print ("exit") Why i am getting this application bouncing in doc menu behavior ? I tried by using NSApplicationMain instead of CFRunLoop in my project, in that case i didnt get this behavior . Does NSApplicationMain does some extra work before starting NSRunLoop which i am not doing while using CFRunLoop, which is showing this toggling/Bouncing application icon in Dock menu ? or Is this bouncing app icon issue is related to run loop i am using which is CFRunLoop ? Note : If i dont use a bundled application and use a commandline application then i am able to do all steps in worker thread and exit main thread as i wanted after finishing my work . But i need to do all this in application which can be launched using double clicking (bundled applcation). If not by using CFRunLoop, then how can i achive this ? - Create a application which shows no UI and do all work in worker thread while main thread is blocked. Once work is done unblock main thread and exit. And user should be able to launch application using double click the application icon.
3
0
388
Mar ’25
Testing XPC Code With an Anonymous Listener using Low Level C APIs
I have implemented a XPC server using C APIs. I want to write unit tests for it. I came across the following links that use Swift APIs- Testing and Debugging XPC Code With an Anonymous Listener TN3113 I have tried to write anonymous listener code and the client code in the same file, using C APIs- #include <unistd.h> #include <syslog.h> #include <pthread.h> #include <stdio.h> #include <xpc/xpc.h> #include <xpc/connection.h> #include <CoreFoundation/CoreFoundation.h> static void Anon_Client_Connection_Handler(xpc_connection_t connection, xpc_object_t clientMessage) { const char *description = xpc_copy_description(clientMessage); printf("Event received - %s\n", description); free((void *)description); xpc_type_t type = xpc_get_type(clientMessage); if (type == XPC_TYPE_ERROR) { if (clientMessage == XPC_ERROR_CONNECTION_INVALID) printf("Client_Connection_Handler received invalid connection n"); else if (clientMessage == XPC_ERROR_TERMINATION_IMMINENT) printf("Client_Connection_Handler received termination notice n"); } else { const char *clientMsg = xpc_dictionary_get_string(clientMessage, "message"); printf("Received from client: %s ", clientMsg); } } static void Anon_Listener_Connection_Handler(xpc_connection_t connection) { printf("Anon_Listener_Connection_Handler called, setting up event handler \n"); xpc_connection_set_event_handler(connection, ^(xpc_object_t clientMessage) { printf("Processing the connection! \n"); Anon_Client_Connection_Handler(connection, clientMessage); }); xpc_connection_resume(connection); } int main(int argc, const char *argv[]) { xpc_connection_t anon_listener = xpc_connection_create(NULL, NULL); xpc_connection_set_event_handler(anon_listener, ^(xpc_object_t clientConnection) { printf("Client tried to connect \n"); Anon_Listener_Connection_Handler(clientConnection); }); xpc_connection_resume(anon_listener); printf("\nINFO Anonymous connection resumed"); xpc_object_t anon_endpoint = xpc_endpoint_create(anon_listener); xpc_connection_t clientConnection = xpc_connection_create_from_endpoint(anon_endpoint); xpc_object_t message = xpc_dictionary_create(NULL, NULL, 0); xpc_dictionary_set_string(message, "message", "client's message"); xpc_connection_send_message_with_reply(clientConnection, message, dispatch_get_main_queue(), ^(xpc_object_t event) { printf("\nINFO inside reply"); const char *description = xpc_copy_description(event); printf("\nINFO %s",description); free((void *)description); }); xpc_release(message); xpc_release(anon_listener); printf("\nINFO Releasing listener"); xpc_release(anon_endpoint); printf("\nINFO Releasing endpoint"); // dispatch_main(); return 0; } and this is the output I get INFO Anonymous connection resumed INFO Releasing listener INFO Releasing endpoint I am not able to connect to the client and exchange messages. Where am I going wrong?
1
1
306
Mar ’25
MacOS Application as a daemon or in non-interaction mode
We are building a 'server' application that can either run as a daemon or can run in background without showing any GUI. Basically, the end user can either configure this to run as a daemon so that it can be tied to the user's session or will launch the process which user will start and quit as needed. I wanted to understand what is the recommended mechanism for such an application from Apple - Should this application be built as a macOS Bundle ? Apple documentation also says that we should not daemonize the process by calling fork. Hence if we create a unix-style executable, will I not need to fork to make it run in a detached state when I launch the executable via double-click ? [Reference Link] Is it fine to have an application on macOS which is a bundle but does not show any UI when launched by double click on the app-icon or via 'open'? While we have been able to achieve this by using NSApplicationMain and not showing the UI, was wondering if using CFRunLoop is best for this case as it is a non-gui application. If we can get the right documentation link or recommendations on how we should build such an application which can run in a non-gui mode and also in a daemonized manner, it will help us. Should the application be always built as a macos bundle or should it be a unix-style executable to support both the cases - by the same application/product and how should we look at the distribution of such applications.
4
1
452
Mar ’25
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
294
Mar ’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
334
Mar ’25
How to check for cancellation of background task
When using the old withTaskCancellationHandler(operation:onCancel:isolation:) to run background tasks, you were notified that the background task gets cancelled via the handler being called. SwiftUI provides the backgroundTask(_:action:) modifier which looks quite handy. However how can I check if the background task will be cancelled to avoid being terminated by the system? I have tried to check that via Task.isCancelled but this always returns false no matter what. Is this not possible when using the modifier in which case I should file a bug report? Thanks for your help
0
0
220
Mar ’25