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

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
63
Apr ’25
BGAppRefreshTask expires after few seconds (2-5 seconds).
I can see a number of events in our error logging service where we track expired BGAppRefreshTask. We use BGAppRefreshTask to update metadata. By looking into those events I can see most of reported expired tasks expired around 2-5 seconds after the app was launched. The documentations says: The system decides the best time to launch your background task, and provides your app up to 30 seconds of background runtime. I expected "up to 30 seconds" to be 10-30 seconds range, not that extremely short. Is there any heuristic that affects how much time the app gets? Is there a way to tell if the app was launched due to the background refresh task? If we have this information we can optimize what the app does during those 5 seconds. Thank you!.
8
0
126
Apr ’25
Question about BGAppRefreshTask approach for medication scheduling app
I'm developing a medication scheduling app similar to Apple Health's Medications feature, and I'd like some input on my current approach to background tasks. In my app, when a user creates a medication, I generate ScheduledDose objects (with corresponding local notifications) for the next 2 weeks and save them to SwiftData. To ensure this 2-week window stays current, I've implemented a BGAppRefreshTask that runs daily to generate new doses as needed. My concern is whether BGAppRefreshTask is the appropriate mechanism for this purpose. Since I'm not making any network requests but rather generating and storing local data, I'm questioning if this is the right approach. I'm also wondering how Apple Health's Medications feature handles this kind of scheduling. Their app seems to maintain future doses regardless of app usage patterns. Has anyone implemented something similar or can suggest the best background execution API for this type of scenario? Thanks for any guidance you can provide.
2
0
101
Apr ’25
APP Background Keep-Alive
Dear Apple: We are developing an app for file sharing between mobile devices. We want to create an iOS app that can continue sharing files with other devices even when it is running in the background. We are using WLAN channels for file sharing. Could you please advise on which background persistence measures we should use to ensure the iOS app can maintain file transfer when it goes to the background? Thank you.
1
0
74
Apr ’25
iOS BGTaskScheduler
Hi! I'm trying to submit a task request into BGTaskScheduler when I background my app. The backgrounding triggers an update of data to a shared app groups container. I'm currently getting the following error and unsure where it's coming from: *** Assertion failure in -[BGTaskScheduler _unsafe_submitTaskRequest:error:], BGTaskScheduler.m:274 Here is my code: BGAppRefreshTaskRequest *request = [[BGAppRefreshTaskRequest alloc] initWithIdentifier:kRBBackgroundTaskIdentifier]; NSError *error = nil; bool success = [[BGTaskScheduler sharedScheduler] submitTaskRequest:request error:&error];
7
0
117
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
70
Apr ’25
Working with Input/Output stream with Swift 6 and concurrency framework
Hello, I am developing an application which is communicating with external device using BLE and L2CAP. I wonder what are the best practices of using Input & Output streams that are established with L2CAP connection when working with Swift 6 concurrency model. I've been trying to find some examples and hints for some time now but unfortunately there isn't much available. One useful thread I've found is: https://developer.apple.com/forums/thread/756281 but it does not offer much insight into using eg. actor model with streams. I wonder if something has changed in this regards? Also, are there any plans to migrate eg. CoreBluetooth stack to new swift 6 concurrency ?
2
0
91
Apr ’25
Launch Host App from Share Extension
Hi! Could you please point me to the official documentation or recommended approach for launching the host app from a Share Extension? The scenario is: The user is sharing some text to my app. I need launch App and show this text. At the moment, I'm using the following hack: let selector = NSSelectorFromString("sharedApplication") if let app = UIApplication.perform(selector)?.takeUnretainedValue() as? UIApplication, app.responds(to: #selector(UIApplication.open(_:options:completionHandler:))) { app.open(url, options: [:], completionHandler: nil) } This does work, but it's terrible. So, the question: What is the official way to open the host app from within a Share Extension? Thanks!
2
0
107
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 : <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs$ <plist version="1.0"> <dict> <key>Label</key> <string>com.example.TWGUI.agent</string> <key>ProgramArguments</key> <array> <string>Contents/MacOS/TWAgent</string> </array> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <true/> </dict> </plist> 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 : <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>BuildMachineOSBuild</key> <string>23C71</string> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>TWGUI</string> <key>CFBundleIdentifier</key> <string>com.example.TWAgent</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>TWGUI</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSupportedPlatforms</key> <array> <string>MacOSX</string> </array> <key>CFBundleVersion</key> <string>1</string> <key>DTCompiler</key> <string>com.apple.compilers.llvm.clang.1_0</string> <key>DTPlatformBuild</key> <string></string> <key>DTPlatformName</key> <string>macosx</string> <key>DTPlatformVersion</key> <string>14.2</string> <key>DTSDKBuild</key> <string>23C53</string> <key>DTSDKName</key> <string>macosx14.2</string> <key>DTXcode</key> <string>1510</string> <key>DTXcodeBuild</key> <string>15C65</string> <key>LSMinimumSystemVersion</key> <string>14.2</string> </dict> </plist> 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
80
Apr ’25
earliestBeginDate timezone
I'm trying to schedule a background task that will run on an iPhone and I'm looking into creating a task request using BGProcessingTaskRequest and scheduled it using BGTaskScheduler.shared.submit(). Per earliestBeginDate documentation, this property can be used to specify the earliest time a background task will be launched by OS. All clear here. However, the question is: how is the value interpreted with respect to timezone ? Is the specified date in device timezone ? Is GMT ? Is something else ?
2
0
52
Apr ’25
XPC - performance/load testing
I have an XPC server running on macOS and want to perform comprehensive performance and load testing to evaluate its efficiency, responsiveness, and scalability. Specifically, I need to measure factors such as request latency, throughput, and how well it handles concurrent connections under different load conditions. What are the best tools, frameworks, or methodologies for testing an XPC service? Additionally, are there any best practices for simulating real-world usage scenarios and identifying potential bottlenecks?
1
1
81
Apr ’25
Launch daemon running but XPC is down
Hello, I have a question about a edge case scenario. Before that some info on my project- I have a launchdaemon that carries out some business logic, it also has XPC listener (built using C APIs). Question- Can there be a situation when the daemon is up and running but the XPC listener is down(due to some error or crash)? If yes then do I need to handle it in my code or launchd will handle it? when the daemon is stopped or shut down, how do I stop the XPC listener? After getting listener object from xpc_connection_create_mach_service should I just call xpc_connection_cancel followed by a call to xpc_release? Thanks! K
3
0
108
Apr ’25
Background processing question
Hi, I have a hard time getting my head wrapped around the possibilities of running a app or a task in a app in the background. I have a app where I utilize MusicKit to create a playlist in Apple Music, and add songs to the playlist. Now the songs added are picked from choices made by the user, and the total number of songs to add is 75, and that takes some time. And if the user switches to a different app or the phone is locked, the add songs logic stops, and then starts again as soon as the app is active again. What I am trying to achieve is of course for this to keep processing also when the app is not active, so basically to keep it running in the background. But this is where I struggle to understand how I can do that - The available choice seems to be BGTaskScheduler, but that just does not seem correct. From what I understand it just schedules a task, and it will be processed whenever the app or phone "feels like it" (again, my understanding, might be wrong), and that won't work in my scenario. I want the task to start when the user taps a button, and just keep running until it is finished, regardless of if the app is active or not. Any pointers, tips, advices out there on how I can achieve this?
2
0
58
Apr ’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
63
Mar ’25
How to correctly access and handle background operations on IOS
Hello, aspiring programmer here. I am developing a StepCounter APP, which keeps track of how many steps I have taken and sends to an MQTT server. I am trying to make this happen even while the app is not in focus, but so far I have not been able to get this working. First tried with silent background music, which seemed pretty inconsistent and inpractical, since I usually play youtube videoes while walking, making the app stop with its silent audio. Then tried GPS, which didnt really do anything (could be implementation problem). Has anyone made background processing work for their apps?
1
0
109
Mar ’25
Is background processing even possible?
Hello, aspiring programmer here. I am developing a StepCounter APP, which keeps track of how many steps I have taken and sends to an MQTT server. I am trying to make this happen even while the app is not in focus, but so far I have not been able to get this working. First tried with silent background music, which seemed pretty inconsistent and inpractical, since I usually play youtube videoes while walking, making the app stop with its silent audio. Then tried GPS, which didnt really do anything (could be implementation problem). Has anyone made background processing work for their apps?
1
0
73
Mar ’25
SMAppService - How does this work?
I'm a developer using Lazarus Pascal, so converting ObjC and Swift comes with its challenges. I'm trying to figure how to properly use SMAppService to add my application as a login item for the App Store. I have learned that the old method (< macOS 13) uses a helper tool, included in the app bundle, which calls the now deprecated SMLoginItemSetEnabled. Now this is already quite a pain to deal with if you're not using XCode, not to mention converting the headers being rather complicated when you're not experienced with doing this. The "new" method (as of macOS 13) is using SMAppService. Can anyone explain how to use this? The documentation (for me anyway) is a not very clear about that and neither are examples that can be found all over the Internet. My main question is: Can I now use the SMAppService functions to add/remove a login item straight in my application, or is a helper tool still required?
3
0
101
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
98
Mar ’25
Effect of app nap of 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? When the application is inactive and the system is either in sleep mode or locked, does the timer’s tolerance get affected? In other words, will the timer fire with any additional delay compared to its scheduled time under these conditions?
1
0
55
Mar ’25
Service Showing "Not Responding" in Activity Monitor Despite Running Threads.
I am encountering an issue with my application, BloxOneEndpoint.pkg, which includes two services: rc_service_infoblox – Runs as the root user. Controller Application – Runs as a normal user. Although a thread within rc_service_infoblox is running fine and performing its expected tasks, I notice that the service appears as "Not Responding" in Activity Monitor. Despite normal functionality, this status is concerning, as it may indicate some issue to customer. I would appreciate any insights into why this might be happening and how to resolve it. Is there a specific API or mechanism I should use to ensure the service remains in a "Running" state in Activity Monitor? Thank you for your guidance.
13
0
153
Mar ’25