Processes & Concurrency

RSS for tag

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

Concurrency Documentation

Post

Replies

Boosts

Views

Activity

Sensorkit - Troubleshooting SRErrorDataInaccessible in Background Fetch with SensorKit
Hello, I am currently developing an iOS application using SensorKit. I encountered an issue when attempting to fetch SensorKit data in the background using background tasks (appRefresh, processing). The following error occurs: In the delegate function func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, failedWithError error: any Error) {}, I receive the error: SRErrorDataInaccessible. In code specific manner: start and handle background fetch (appRefresh) func handleAppRefreshTask(task: BGAppRefreshTask) { logger.logWithServer(level: .default, message: "background fetch start", category: String(describing: BackgroundTaskManager.self)) scheduleBackgroundFetch() let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 let fetchOperation = FetchOperation() queue.addOperation(fetchOperation) task.expirationHandler = { self.logger.logWithServer(level: .error, message: "background fetch expirated", category: String(describing: BackgroundTaskManager.self)) queue.cancelAllOperations() } fetchOperation.completionBlock = { task.setTaskCompleted(success: !fetchOperation.isCancelled) } } Background fetch operation class class FetchOperation: Operation { override func main() { guard !isCancelled else { return } Task { // this function will execute fetch request for all user allowed sensorReader, 'func fetch(_ request: SRFetchRequest)' await SensorkitManager.shared.startFetchAndUpload() } } } I have the following questions: Is it possible to fetch SensorKit data in the background? If it is possible, why does the above error occur? If it is possible, could you provide the solution code and the correct workflow to avoid this error? Thank you.
2
0
382
Aug ’24
How to Open Privacy & Security Location Services Programmatically
I'm an iOS mobile developer working on handling location permissions. I've observed that some apps, even recent ones available on the App Store, can automatically navigate to the settings path: Settings -> Privacy & Security -> Location Services when the device's location services are turned off. However, most examples and best practices recommend using UIApplication.openSettingsURLString, which does not meet my requirements. This function only opens the app's specific location permissions, not the device-wide location services toggle. I'm looking for a way to programmatically open the Privacy & Security -> Location Services settings page directly. Any insights or solutions for achieving this functionality in a compliant and sustainable manner would be greatly appreciated. Thank you in advance for your help!
1
0
336
Aug ’24
How to get which app is currently being used by user
Hello! I'm designing an app that tracks users' screen time and shares it with each other. I've looked extensively into the ScreenTimeAPI and it seems as if Apple doesn't allow any way to share screen time data. Even with the user's permission. I was wondering whether there is a way that my app (running in the background) would be able to get whether the user was currently using the notes app (or any other app). I was looking into the AppTrackingTransparency framework to see if this functionality was at all possible, but came up short of finding an answer. Is this possible? My guess is no but still wanted to check.
1
0
316
Jul ’24
serial dispatch_queue_t crashed
background info: I dispatch async task to main queue in an es_handler_block_t(client subscribe open, create, exit, close events and mute all processes except DesktopServicesHelper). crash happened kinda randomly. most likely to happen when I copy a folder(contains a lot of files) in a volume to another volume. here's the crashed part of the diagnostic report . Thread 9 Crashed:: Dispatch queue: com.apple.main-thread 0 libsystem_kernel.dylib 0x18c6e2a60 __pthread_kill + 8 1 libsystem_pthread.dylib 0x18c71ac20 pthread_kill + 288 2 libsystem_c.dylib 0x18c627a20 abort + 180 3 libc++abi.dylib 0x18c6d1d30 abort_message + 132 4 libc++abi.dylib 0x18c6c1fe8 demangling_terminate_handler() + 348 5 libobjc.A.dylib 0x18c3601d0 _objc_terminate() + 144 6 libc++abi.dylib 0x18c6d10f4 std::__terminate(void (*)()) + 16 7 libc++abi.dylib 0x18c6d1098 std::terminate() + 108 8 libdispatch.dylib 0x18c56a3fc _dispatch_client_callout + 40 9 libdispatch.dylib 0x18c571a14 _dispatch_lane_serial_drain + 748 10 libdispatch.dylib 0x18c572578 _dispatch_lane_invoke + 432 11 libdispatch.dylib 0x18c57bea8 _dispatch_root_queue_drain + 392 12 libdispatch.dylib 0x18c57c6b8 _dispatch_worker_thread2 + 156 13 libsystem_pthread.dylib 0x18c716fd0 _pthread_wqthread + 228 14 libsystem_pthread.dylib 0x18c715d28 start_wqthread + 8 Thread 9 crashed with ARM Thread State (64-bit): x0: 0x0000000000000000 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x0000000000000000 x4: 0x000000018c6d62cb x5: 0x000000016c1eed20 x6: 0x000000000000006e x7: 0x0000000000000000 x8: 0x851ef9fdee51098d x9: 0x851ef9fc824ff98d x10: 0x0000000000000200 x11: 0x000000000000000b x12: 0x0000000000000000 x13: 0x00000000001ff800 x14: 0x00000000000007fb x15: 0x00000000a5a0204e x16: 0x0000000000000148 x17: 0x00000001fe792c30 x18: 0x0000000000000000 x19: 0x0000000000000006 x20: 0x000000016c1ef000 x21: 0x0000000000004003 x22: 0x000000016c1ef0e0 x23: 0x000000016c1ef0e0 x24: 0x00000001f442b6a8 x25: 0x0000000000000000 x26: 0x0000000000000000 x27: 0x0000600003664800 x28: 0x0000000000000000 fp: 0x000000016c1eec90 lr: 0x000000018c71ac20 sp: 0x000000016c1eec70 pc: 0x000000018c6e2a60 cpsr: 0x40001000 far: 0x0000000000000000 esr: 0x56000080 Address size fault
1
0
336
Jul ’24
Nice vs Priority on MacOS
I write programs to do calculations. In order to automate some things I setup my Mac to consume a queue of jobs and a cron will check the queue and then run them through. I noticed that cron jobs run so much slower. As root I am running all the commands at nice -n -100 (yes I know -20 is the limit) if I run this command from the terminal it take 62 seconds. Checking the ps this is what I see: UID PID PPID F CPU PRI NI SZ RSS WCHAN S ADDR TTY TIME CMD STIME 0 17826 17195 4006 0 31 -20 413217088 581472 - R<+ 0 ttys000 16:11.07 /usr/local/bin/M 0.358 12:41PM Now comparing that to the cron'd job this same calculations will take 441 seconds. The ps comes out to: UID PID PPID F CPU PRI NI SZ RSS WCHAN S ADDR TTY TIME CMD STIME 0 18231 18230 4004 0 20 -20 411514512 515632 - R< 0 ?? 28:16.72 /usr/local/bin/M 12:47PM This is 7x slower! Both processes are at -20 NICE, but the priority for the cron job is 20 while running from terminal is 31. So I am guessing that priority is the mitigating factor here. I can't seem to figure out how to change the priority of the job. Lots resources out there just seem to think by changing nice you also change priority. But that is not the case. The question I have is how do I change the priority of a cron job (or any job in fact). I am running on a MacBook Pro (2013). I was thinking maybe Apple Mac Pro desktops could be setup differently but I just don't know.
2
0
367
Jul ’24
Capturing NSXPCConnectionCodeSigningRequirementFailure in XPC service
I’m working on a launch daemon. I’m in the process of adding setCodeSigningRequirement to both sides of the connection, starting with the XPC service. I’ve already made it so that the service calls setCodeSigningRequirement on a new connection passed to the listener method of NSXPCListenerDelegate. It works and the connection does get invalidated. The launch daemon logs stdout and stderr to a file already. So I figured that if a connection gets invalidated because of a code signing failure, it’d be nice to NSLog this to make it easier for users to debug what’s going on, without forcing them to use Console.app. The docs for setCodeSigningRequirement include an example of how to capture this error on the client side, when the client calls that method. What I cannot figure out is how to capture this error on the side of the XPC service. I could use setInvalidationHandler, but the problem with it is that a connection can be invalidated for a myriad of reasons and the handler doesn’t know what happened. Is there perhaps an equivalent of remoteObjectProxyWithErrorHandler but for the service side of the connection?
4
0
444
Jul ’24
Using cooperative cancellation in `expirationHandler` of `beginBackgroundTask(...)`
Let's say I have a Task that I want to extend into the background with beginBackgroundTask(expirationHandler:). Furthermore, I'd like to leverage cooperative cancelation of subtasks when responding to the expiration handler. Unfortunately, the expirationHandler: closure parameter is not async, so I'm unable to do something like: actor MyTaskManagerOne { var backgroundID = UIBackgroundTaskIdentifier.invalid func start() { Task { let doTheWorkTask = Task { await self.doTheWork() } backgroundID = await UIApplication.shared.beginBackgroundTask { doTheWorkTask.cancel() // next line: compile error, since not an async context await doTheWorkTask.value // ensure work finishes up // next line: generates MainActor compilation warnings despite docs allowing it UIApplication.shared.endBackgroundTask(self.backgroundID) } await doTheWorkTask.value } } func doTheWork() async {} } So instead, I think I have to do something like this. It, however, generates runtime warnings, since I'm not directly calling endBackgroundTask(_:) at the end of the expirationHandler: actor MyTaskManagerTwo { var backgroundID = UIBackgroundTaskIdentifier.invalid func start() { Task { let doTheWorkTask = Task { await self.doTheWork() } backgroundID = await UIApplication.shared.beginBackgroundTask { doTheWorkTask.cancel() // 1. not calling endBackgroundTask here generates runtime warnings } await doTheWorkTask.value // 2. even though endBackgroundTask gets called // here (as long as my cooperative cancellation // implementations abort quickly in `doTheWork()`) await UIApplication.shared.endBackgroundTask(self.backgroundID) } } func doTheWork() async {} } As best I can tell, the MyTaskManagerTwo actor works and does not cause a watchdog termination (as long as cancellation is sufficiently fast). It is, however, producing the following runtime warning: Background task still not ended after expiration handlers were called: <_UIBackgroundTaskInfo: 0x302753840>: taskID = 2, taskName = Called by libswift_Concurrency.dylib, from <redacted>, creationTime = 9674 (elapsed = 28). This app will likely be terminated by the system. Call UIApplication.endBackgroundTask(_:) to avoid this. Is the runtime warning ok to ignore in this case?
3
0
430
Jul ’24
Assertion failure during deinit due to... DispatchSourceTimer?
I have var idleScanTimer = DispatchSource.makeTimerSource() as a class ivar. When the object is started, I have self.idleScanTimer.schedule(deadline: .now(), repeating: Double(5.0*60)) (and it sets an event handler, that checks some times.) When the object is stopped, it calls self.idleScanTimer.cancel(). At some point, the object containing it is deallocated, and ... sometimes, I think, not always, it crashes: Crashed Thread: 61 Dispatch queue: NEFlow queue [...] Application Specific Information: BUG IN CLIENT OF LIBDISPATCH: Release of an inactive object [...] Thread 61 Crashed:: Dispatch queue: NEFlow queue 0 libdispatch.dylib 0x7ff81c1232cd _dispatch_queue_xref_dispose.cold.2 + 24 1 libdispatch.dylib 0x7ff81c0f84f6 _dispatch_queue_xref_dispose + 55 2 libdispatch.dylib 0x7ff81c0f2dec -[OS_dispatch_source _xref_dispose] + 17 3 com.kithrup.simpleprovider 0x101df5fa7 MyClass.deinit + 87 4 com.kithrup.simpleprovider 0x101dfbdbb MyClass.__deallocating_deinit + 11 5 libswiftCore.dylib 0x7ff829a63460 _swift_release_dealloc + 16 6 com.kithrup.simpleprovider 0x101e122f4 0x101de7000 + 176884 7 libswiftCore.dylib 0x7ff829a63460 _swift_release_dealloc + 16 8 libsystem_blocks.dylib 0x7ff81bfdc654 _Block_release + 130 9 libsystem_blocks.dylib 0x7ff81bfdc654 _Block_release + 130 10 libdispatch.dylib 0x7ff81c0f3317 _dispatch_client_callout + 8 11 libdispatch.dylib 0x7ff81c0f9317 _dispatch_lane_serial_drain + 672 12 libdispatch.dylib 0x7ff81c0f9dfd _dispatch_lane_invoke + 366 13 libdispatch.dylib 0x7ff81c103eee _dispatch_workloop_worker_thread + 753 14 libsystem_pthread.dylib 0x7ff81c2a7fd0 _pthread_wqthread + 326 15 libsystem_pthread.dylib 0x7ff81c2a6f57 start_wqthread + 15 I tried changing it to an optional and having the deinit call .cancel() and set it to nil, but it still crashes. I can't figure out how to get it deallocated in a small, standalone test program.
4
0
537
Jul ’24
Accessing SafariServices from Sandboxed LaunchAgent
I'm attempting to reload a Safari Content Blocker from within a sandboxed command-line tool configured as a LaunchAgent. However, when I use SFContentBlockerManager to reload the content blocker, I encounter the error SFErrorDomain Code=1: Unavailable error. Is it possible to reload a content blocker from a LaunchAgent? If so, how can it be done? // // main.swift // BlockerUpdater // // Created by Sebastian Livoni on 30/06/2024. // import Foundation import SafariServices // Function to reload content blocker asynchronously func reloadContentBlocker() async { NSLog("Hello, World!") do { try await SFContentBlockerManager.reloadContentBlocker(withIdentifier: "me.livoni.blocker.dns") NSLog("Reload complete") } catch { NSLog("Failed to reload content blocker: \(error.localizedDescription)") } } // Main entry point for async code @main struct BlockerUpdater { static func main() async { await reloadContentBlocker() } }
2
0
407
Jul ’24
How often should getTimeline be called in widgetkit?
Hi, I am implementing a widget where I make some network calls. I have set the timelineprovider to update on end, and I have about an hour of widgetkit entries going for each timeline. I notice that the getTimeline function is called an arbitrary amount of times, usually between 2-5 when my widget fetches new entries for the widget. I was under the impression that it should only call the getTimeline function once, and use the entires for all of my widgets (I 3 widgets in total, two for the lock screen and one for home screen). Am I missing something when it comes to understanding the basic lifecycle? Anyone else having these issues? I am using XCode 15.3 and developing for iOS 17.
1
0
473
Jun ’24
iOS dosen't call didActivateAudioSession
PLATFORM AND VERSION iOS Development environment: Xcode 15.0, macOS 14.4.1, Objective-C Run-time configuration: iOS 17.2.1, DESCRIPTION OF PROBLEM I am developing an application that uses NetworkExtension (VoIP local push function). But iOS sometimes doesn't call didActivateAudioSession after following sequence. Would you tell me why iOS doesn't call didActivateAudioSession ? (I said "sometimes", but once it occurs, it will occur repeatedly) myApp --- CXStartCallAction --->iOS myApp <-- performStartCallAction callback --- iOS myApp --- AVAudioSession setCategory: AVAudioSessionCategoryPlayAndRecord --->iOS myApp --- AVAudioSession setMode: AVAudioSessionModeVoiceChat --->iOS myApp <-- didActivateAudioSession callback ----iOS I suspect that myApp cannot acquire an AVAudioSession if another app is already using AVAudioSession. [QUESTION1] Is my guess correct? Should I consider another cause? [QUESTION2] If my guess is correct, how can I prove if another app is already using an AVAudioSession? This issue is based on a customer complaint, but the customer said they don't use any other apps. Best Regards,
5
0
642
Jun ’24
Background process for email encryption
Hello! My startup is developing a Desktop application for Windows and macOS for encrypting email in local networks. Email encryption in sending applications is planned to be carried out using the S/MIME protocol. The private key is stored on the user's smartphone (we have a requirement from our customers), and at certain moments we simulate the work of a smart card over the WebSocket protocol. In addition, there are policies requiring constant connection of a smart card. However, unlike Android, the user must manually launch the application each time to sign a letter. Is it possible to make sure that the WebSocket connection does not interrupt in the background? We received many negative reviews from iOS users because of this. Or help us please, what protocol can be used for background emulation of smart card operations?
1
0
347
Jun ’24
macOS应用,沙盒化之后无法启动脚本
我添加了相应服务的xx.plist,并在shell脚本中使用launchctl load -w "$HOME/Library/LaunchAgents/com.xx.xx.plist" launchctl start com.xx.xx.local 启动,脚本名称为local,当我给app加上沙盒功能之后,我使用 let installerPath = bundle.path(forResource: "local.sh", ofType: nil) let task = Process.launchedProcess(launchPath: "/bin/bash", arguments: [installerPath!]) task.waitUntilExit()运行结果,我得到这样 的结果:Load failed: 5: Input/output error Try running launchctl bootstrap as root for richer errors. Unload failed: 5: Input/output error Try running launchctl bootout as root for richer errors. Not privileged to start service.,可以帮助我吗? 我该进行什么操作,才能让我的app正常运行?
0
0
362
Jun ’24
GUI + XPC Service App Architecture Performance
Let's image that someone wants to use a background service to keep track of FSEvents activity, at the file level (a firehose, some might say). I choose this example, to indicate the volume and rate of data transmission in question. I'm not creating a front-end for FSEvents data, but my background service may generate data at a similar pace. The service runs off of user defined document/s that specify the FSEvent background filtering to be applied. Those that match get stored into a database. But filters can match on almost all the data being emitted by FSEvents. The user decides to check on the service's activity and database writes by launching a GUI that sends requests to the background service using XPC. So the GUI can request historic data from a database, but also get a real-time view of what FS events the service is busy filtering. So it's a client-server approach, that's concerned with monitoring an event stream over XPC. I understand XPC is a request/response mechanism, and I might look into using a reverse connection here, but my main concern is one of performance. Is XPC capable of coping with such a high volume of data transmision? Could it cope with 1000s of rows of table data updates per second sent to a GUI frontend? I know there are streaming protocol options that involve a TCP connection, but I really want to stay away from opening sockets.
7
0
535
Jun ’24
BGTaskScheduler on Mac Silicon not scheduling
When I register & schedule a Background Task on an iPad, it runs properly. Running the exact same code on an M1 MacBook Pro, though, never schedules the task. There's no error, just a failure to schedule. After scheduling and calling getPendingTaskRequests, on the iPad you can see that it has a pending task, but not on the Mac. Why would this be? BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifier, using: nil) { [self] task in print("task to run") } do { try BGTaskScheduler.shared.submit(request) BGTaskScheduler.shared.getPendingTaskRequests { [self] tasks in print(tasks.count) //Prints 1 on iPad, prints 0 on Mac } } catch { //Code never comes here. print(error) }
1
0
444
Jun ’24
Open Safari from iOS application
Cannot bring the Safari browser to the foreground from an iOS application while other applications can be opened the same way. STEPS TO REPRODUCE After executing the following code, the browser is not opened: if let url = URL(string: "com-apple-mobilesafari-tab://"), UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [: ], completionHandler: nil) }
1
0
325
Jun ’24