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

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
447
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
364
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
332
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
308
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
298
May ’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
311
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
397
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
304
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
371
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
232
Mar ’25
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
244
Mar ’25
Effect of App Nap on Timer
I'm developing a macOS application that tracks the duration of a user's session using a timer, which is displayed both in the main window and in an menu bar extra view. I have a couple of questions regarding the timer's behavior: What happens to the timer if the user closes the application's window (causing the app to become inactive) but does not fully quit it? Does the timer continue to run, pause, or behave in some other way? Will the app nap feature stop the timer when app is in-active state?
1
0
100
Mar ’25
DispatchSourceTimer Not Firing in Local Push Connectivity Extension When App Is in Foreground and Device Is Locked
Hi, I’m using a Local Push Connectivity Extension and encountering an issue with DispatchSourceTimer. In my extension, I create a DispatchSourceTimer that is supposed to fire every 1 second. It works as expected at first. However, when the app is in the foreground and the device is locked, the timer eventually stops firing after 1–3 hours. The extension process is still alive, and no errors are thrown Has anyone experienced this behavior? Is this a known limitation for timers inside NEAppPushProvider, or is the extension being deprioritized silently by the system? Any insights or suggestions would be greatly appreciated. Thanks!
2
0
67
Apr ’25
Help me implement SMAppServices
I have followed these steps as mentioned in this link :(https://developer.apple.com/forums/thread/721737) My projects app bundle structure is like this : TWGUI.app TWGUI.app/Contents TWGUI.app/Contents/_CodeSignature TWGUI.app/Contents/_CodeSignature/CodeResources TWGUI.app/Contents/MacOS TWGUI.app/Contents/MacOS/TWAgent TWGUI.app/Contents/MacOS/TWGUI TWGUI.app/Contents/Resources TWGUI.app/Contents/Library TWGUI.app/Contents/Library/LaunchAgents TWGUI.app/Contents/Library/LaunchAgents/com.example.TWGUI.agent.plist TWGUI.app/Contents/Info.plist TWGUI.app/Contents/PkgInfo TWGUI is my main GUI App , i which i want to embed TWAgent (a command line tool target) and register it using SMAppServices so that launchd can launch it. In TWGUI, code for registering to launchd using SMAppServices is structure as follow : import SwiftUI import ServiceManagement struct ContentView: View { let agent = SMAppService.agent(plistName: "com.example.TWGUI.agent.plist") var body: some View { VStack { Button("Register Agent") { RegisterAgent () } .padding() Button("Unregister Agent") { UnregisterAgent () } .padding() } } func RegisterAgent() { DispatchQueue.global(qos: .background).async { do { print("Registering Agent. Status: \(agent.status.rawValue)") try agent.register() print("Agent registered") } catch { print("Failed to register agent: \(error)") } } } func UnregisterAgent() { DispatchQueue.global(qos: .background).async { do { print("Unregistering Agent. Status: \(agent.status.rawValue)") try agent.unregister() print("Agent unregistered") } catch { print("Failed to unregister agent: \(error)") } } } } com.example.TWGUI.agent.plist : &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs$ &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;Label&lt;/key&gt; &lt;string&gt;com.example.TWGUI.agent&lt;/string&gt; &lt;key&gt;ProgramArguments&lt;/key&gt; &lt;array&gt; &lt;string&gt;Contents/MacOS/TWAgent&lt;/string&gt; &lt;/array&gt; &lt;key&gt;RunAtLoad&lt;/key&gt; &lt;true/&gt; &lt;key&gt;KeepAlive&lt;/key&gt; &lt;true/&gt; &lt;/dict&gt; &lt;/plist&gt; I have used ProgramArguements instead of using Program in above plist because i was getting this error when i was using Program earlier : Registering Agent. Status: 3 Failed to register agent: Error Domain=SMAppServiceErrorDomain Code=111 "Invalid or missing Program/ProgramArguments" UserInfo={NSLocalizedFailureReason=Invalid or missing Program/ProgramArguments} TWGUI apps Info.plist is : &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;BuildMachineOSBuild&lt;/key&gt; &lt;string&gt;23C71&lt;/string&gt; &lt;key&gt;CFBundleDevelopmentRegion&lt;/key&gt; &lt;string&gt;en&lt;/string&gt; &lt;key&gt;CFBundleExecutable&lt;/key&gt; &lt;string&gt;TWGUI&lt;/string&gt; &lt;key&gt;CFBundleIdentifier&lt;/key&gt; &lt;string&gt;com.example.TWAgent&lt;/string&gt; &lt;key&gt;CFBundleInfoDictionaryVersion&lt;/key&gt; &lt;string&gt;6.0&lt;/string&gt; &lt;key&gt;CFBundleName&lt;/key&gt; &lt;string&gt;TWGUI&lt;/string&gt; &lt;key&gt;CFBundlePackageType&lt;/key&gt; &lt;string&gt;APPL&lt;/string&gt; &lt;key&gt;CFBundleShortVersionString&lt;/key&gt; &lt;string&gt;1.0&lt;/string&gt; &lt;key&gt;CFBundleSupportedPlatforms&lt;/key&gt; &lt;array&gt; &lt;string&gt;MacOSX&lt;/string&gt; &lt;/array&gt; &lt;key&gt;CFBundleVersion&lt;/key&gt; &lt;string&gt;1&lt;/string&gt; &lt;key&gt;DTCompiler&lt;/key&gt; &lt;string&gt;com.apple.compilers.llvm.clang.1_0&lt;/string&gt; &lt;key&gt;DTPlatformBuild&lt;/key&gt; &lt;string&gt;&lt;/string&gt; &lt;key&gt;DTPlatformName&lt;/key&gt; &lt;string&gt;macosx&lt;/string&gt; &lt;key&gt;DTPlatformVersion&lt;/key&gt; &lt;string&gt;14.2&lt;/string&gt; &lt;key&gt;DTSDKBuild&lt;/key&gt; &lt;string&gt;23C53&lt;/string&gt; &lt;key&gt;DTSDKName&lt;/key&gt; &lt;string&gt;macosx14.2&lt;/string&gt; &lt;key&gt;DTXcode&lt;/key&gt; &lt;string&gt;1510&lt;/string&gt; &lt;key&gt;DTXcodeBuild&lt;/key&gt; &lt;string&gt;15C65&lt;/string&gt; &lt;key&gt;LSMinimumSystemVersion&lt;/key&gt; &lt;string&gt;14.2&lt;/string&gt; &lt;/dict&gt; &lt;/plist&gt; TWAgent target has main.swift file which does this : import Foundation let startTime = CFAbsoluteTimeGetCurrent() func logTimeSinceStart() { let elapsedTime = CFAbsoluteTimeGetCurrent() - startTime NSLog("Time since program started: \(elapsedTime) seconds") } func startLoggingTime() { Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in logTimeSinceStart() } } // Start logging time startLoggingTime() // Keep the run loop running CFRunLoopRun() I followed these exact same steps in another project earlier and my agent was getting registered, although i lost that project due to some reasons. But now i am getting this error when i am registering or unregistering agent using SMAppServices from the code above : Registering Agent. Status: 3 Failed to register agent: Error Domain=SMAppServiceErrorDomain Code=1 "Operation not permitted" UserInfo={NSLocalizedFailureReason=Operation not permitted} I tried diffrent fixes for like this : Moved app bundle to /applications folder Gave permission for full disc access to this app . Code sign again (both agent and TWGUI ... But nothing seems to work , getting same error. I tried to launch agent using : Launchctl load com.example.TWGUI.agent.plist and it worked , so there is no issue with my plist implementation. Can someone help me understand how can i solve this issue ? or if i am following right steps ? Can give steps need to follow to implement this and steps so that i can register and start my agent using SMAppServices? And i also tried the project give in apples official documentation : [https://developer.apple.com/documentation/servicemanagement/updating-your-app-package-installer-to-use-the-new-service-management-api) but got same error in this project as well .
2
0
88
Apr ’25
Return the results of a Spotlight query synchronously from a Swift function
How can I return the results of a Spotlight query synchronously from a Swift function? I want to return a [String] that contains the items that match the query, one item per array element. I specifically want to find all data for Spotlight items in the /Applications folder that have a kMDItemAppStoreAdamID (if there is a better predicate than kMDItemAppStoreAdamID > 0, please let me know). The following should be the correct query: let query = NSMetadataQuery() query.predicate = NSPredicate(format: "kMDItemAppStoreAdamID > 0") query.searchScopes = ["/Applications"] I would like to do this for code that can run on macOS 10.13+, which precludes using Swift Concurrency. My project already uses the latest PromiseKit, so I assume that the solution should use that. A bonus solution using Swift Concurrency wouldn't hurt as I will probably switch over sometime in the future, but won't be able to switch soon. I have written code that can retrieve the Spotlight data as the [String], but I don't know how to return it synchronously from a function; whatever I tried, the query hangs, presumably because I've called various run loop functions at the wrong places. In case it matters, the app is a macOS command-line app using Swift 5.7 & Swift Argument Parser 1.5.0. The Spotlight data will be output only as text to stdout & stderr, not to any Apple UI elements.
1
0
75
Apr ’25
NSFileCoordinator Swift Concurrency
I'm working on implementing file moving with NSFileCoordinator. I'm using the slightly newer asynchronous API with the NSFileAccessIntents. My question is, how do I go about notifying the coordinator about the item move? Should I simply create a new instance in the asynchronous block? Or does it need to be the same coordinator instance? let writeQueue = OperationQueue() public func saveAndMove(data: String, to newURL: URL) { let oldURL = presentedItemURL! let sourceIntent = NSFileAccessIntent.writingIntent(with: oldURL, options: .forMoving) let destinationIntent = NSFileAccessIntent.writingIntent(with: newURL, options: .forReplacing) let coordinator = NSFileCoordinator() coordinator.coordinate(with: [sourceIntent, destinationIntent], queue: writeQueue) { error in if let error { return } do { // ERROR: Can't access NSFileCoordinator because it is not Sendable (Swift 6) coordinator.item(at: oldURL, willMoveTo: newURL) try FileManager.default.moveItem(at: oldURL, to: newURL) coordinator.item(at: oldURL, didMoveTo: newURL) } catch { print("Failed to move to \(newURL)") } } }
0
0
69
Apr ’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
99
May ’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
143
Apr ’25
Prevent my app from background activity
When I search, it's always people trying to do stuff in the background. I want my app to only do stuff when it is active. And this post https://developer.apple.com/forums/thread/685525 seems to have prevented replies from the start. Which means it's just a documentation page and does not belong in the discussion forums at all, because it prevents all discussion.
1
0
67
May ’25
NSXPCListener only working while Debugging `listener failed to activate: xpc_error=[1: Operation not permitted]`
I am building a Mac app that launch a GUI helper app and use XPC to communicate between them. Main app start a XPC Listener using NSXPCListener(machServiceName: "group.com.mycompany.myapp.xpc") Launch the helper app Helper app connect to the XPC service and listen command from main app. What I observe is the app seems can start XPC listener while I run it via Xcode. If I run the app using TestFlight build, or via the compiled debug binary (same one that I use on Xcode), it cannot start the XPC service. Here is what I see in the Console: [0x600000ef7570] activating connection: mach=true listener=true peer=false name=group.com.mycompany.myapp.xpc [0x600000ef7570] listener failed to activate: xpc_error=[1: Operation not permitted] Both main app and helper app are sandboxed and in the same App Group - if they were not, I cannot connect the helper app to main app. I can confirm the entitlement profiles did contain the app group. If I start the main app via xcode, and then launch the helper app manually via Finder, the helper app can connect to the XPC and everything work. It is not related to Release configuration, as the same binary work while I am debugging, but not when I open the binary manually. For context, the main app is a Catalyst app, and helper app is an AppKit app. To start a XPC listener on Catalyst, I had do it in a AppKit bridge via bundle. Given the app worked on Xcode, I believe this approach can work. I just cannot figure out why it only work while I am debugging. Any pointer to debug this issue is greatly appreciated. Thanks!
3
0
86
May ’25