I tried to use XCTest to test my own project that uses EndpointSecurity, but when I created the esClient I got an error:ES_NEW_CLIENT_RESULT_ERR_NOT_PRIVILEGED, indicating that it was not root.
This makes it impossible for me to do coverage tests for the ESClient application. Is there any way I can implement this ESClient test? If so, how should I use it? The project is a macOS program, if I use gcov, but I find I can't get coverage. Using __gcov_flush will indicate that there is no symbol
#if !TARGET_IPHONE_SIMULATOR
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
setenv("GCOV_PREFIX", [documentsDirectory cStringUsingEncoding:NSUTF8StringEncoding], 1);
setenv("GCOV_PREFIX_STRIP", "13", 1);
#endif
extern void __gcov_flush(void);
__gcov_flush();
#endif
Processes & Concurrency
RSS for tagDiscover how the operating system manages multiple applications and processes simultaneously, ensuring smooth multitasking performance.
Post
Replies
Boosts
Views
Activity
Question:
I'm working on a project in Xcode 16.1, using Swift 6 with iOS 18. My code is working fine in Swift 5, but I'm running into concurrency issues when upgrading to Swift 6, particularly with the @preconcurrency attribute in AVFoundation.
Here is the relevant part of my code:
import SwiftUI
@preconcurrency import AVFoundation
struct OverlayButtonBar: View {
...
let audioTracks = await loadTracks(asset: asset, mediaType: .audio)
...
// Tracks are extracted before crossing concurrency boundaries
private func loadTracks(asset: AVAsset, mediaType: AVMediaType) async -> [AVAssetTrack] {
do {
return try await asset.load(.tracks).filter { $0.mediaType == mediaType }
} catch {
print("Error loading tracks: \(error)")
return []
}
}
}
Issues:
When using @preconcurrency, I get the warning:
@preconcurrency attribute on module AVFoundation has no effect. Suggested fix by Xcode is: Remove @preconcurrency.
But if I remove @preconcurrency, I get both a warning and an error:
Warning: Add '@preconcurrency' to treat 'Sendable'-related errors from module 'AVFoundation' as warnings.
Error: Non-sendable type [AVAssetTrack] returned by implicitly asynchronous call to nonisolated function cannot cross actor boundary. (Class AVAssetTrack does not conform to the Sendable protocol (AVFoundation.AVAssetTrack)). This error comes if I attempt to directly access non-Sendable AVAssetTrack in an async context :
let audioTracks = await loadTracks(asset: asset, mediaType: .audio)
How can I resolve this issue while staying compliant with Swift 6 concurrency rules? Is there a recommended approach to handling non-Sendable types like AVAssetTrack in concurrency contexts?
Appreciate any guidance on making this work in Swift 6, especially considering it worked fine in Swift 5.
Thanks in advance!
Hello,
I’m encountering an issue with the PHPhotoLibrary API in Swift 6 and iOS 18. The code I’m using worked fine in Swift 5, but I’m now seeing the following error:
Sending main actor-isolated value of type '() -> Void' with later accesses to nonisolated context risks causing data races
Here is the problematic code:
Button("Save to Camera Roll") {
saveToCameraRoll()
}
...
private func saveToCameraRoll() {
guard let overlayFileURL = mediaManager.getOverlayURL() else {
return
}
Task {
do {
let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
guard status == .authorized else {
return
}
try await PHPhotoLibrary.shared().performChanges({
if let creationRequest = PHAssetCreationRequest.creationRequestForAssetFromVideo(atFileURL: overlayFileURL) {
creationRequest.creationDate = Date()
}
})
await MainActor.run {
saveSuccessMessage = "Video saved to Camera Roll successfully"
}
} catch {
print("Error saving video to Camera Roll: \(error.localizedDescription)")
}
}
}
Problem Description:
The error message suggests that a main actor-isolated value of type () -> Void is being accessed in a nonisolated context, potentially leading to data races.
This issue arises specifically at the call to PHPhotoLibrary.shared().performChanges.
Questions:
How can I address the data race issues related to main actor isolation when using PHPhotoLibrary.shared().performChanges?
What changes, if any, are required to adapt this code for Swift 6 and iOS 18 while maintaining thread safety and actor isolation?
Are there any recommended practices for managing main actor-isolated values in asynchronous operations to avoid data races?
I appreciate any points or suggestions to resolve this issue effectively.
Thank you!
Coming from windows development, I'm trying to understand macOS architecture and how to do certain things. I've already read the Root and Login Sessions AND Service and Daemons AND User Switch Notifications documentation so will frame the questions accordingly.
On Windows, there's a concept of User Sessions, each of which contain One or more WindowStations, each of which contain One or more Desktops. Each user gets at least 3 desktops (e.g. Login/Lock/UAC, Screensaver, and default desktop). From what I understand about macOS, it only has Sessions and then a single Desktop. Is that correct? i.e. same display surface is used to display user's desktop, screensaver, sudo prompt and lock screen?
What about login screen? Does each user get its own login screen process/window running in their session? or is there a common login screen for all users running in one particular session (root?). How does Fast User switching effect login screen?
In a daemon, is it possible to get active console session ID? console meaning the session being displayed on the monitor, whether its login screen, lock screen, user's desktop etc.
In a daemon, is it possible to get session switch notifications? E.g. user logged-in and now their desktop is being displayed, user logged-out and now we're back on login screen, or user switched to another user (Fast User switching). How do I get notification of such events in daemon?
If no user is logged in which session is pre-login agent running in? and after login does the session ID assigned to pre-login agent stay the same and user's session is assigned a new session ID?
Is there always one and only one pre-login agent running?
Is it possible to launch pre-login agent and user agents on-demand with custom commandline arguments from a daemon?
Hello everyone, I need help with an issue that is unclear to me. I developed an application with Unity and now I'm using xCode to distribute it both outside the App Store and on the App Store. As for the first option, no problem, I was able to build the app and upload it for validation. However, regarding the App Store, I have a problem with "App Sandbox," which seems to be mandatory in this case. My application is essentially a party game where one part functions as a desktop application and another part as a mobile application. The desktop application launches a parallel process (which I included in a group within xcode and signed with my developer ID) that makes the two parts communicate through a socket on the local network. When I enable App Sandbox, it seems that the process is not launched by the main application. I have also enabled the two options, Incoming Connection (server/client), under App Sandbox, but it still did not work. I thank you in advance for the support.Sandbox app + parallel process + LAN Socket
Hi There,
I have to achieve following scenario
Track system event on macosx for shutdown and restart and update one plist with same event via launchAgent
I have tried following code on launchAgent
class MyAgent {
init() {
let notificationCenter = NSWorkspace.shared.notificationCenter
// Register for system shutdown notification
notificationCenter.addObserver(self,
selector: #selector(handleNotification(_:)),
name: NSWorkspace.willPowerOffNotification,
object: nil)
RunLoop.current.run()
}
@objc func handleNotification(_ notification: Notification) {
var logMessage = ""
switch notification.name {
case NSWorkspace.willPowerOffNotification:
os_log("System is going to shut down at", log: log, type: .default)
updatePlistFile(event: "shut down")
let fileName = "example.txt"
let content = "shut down"
createAndWriteFile(fileName: fileName, content: content)
logMessage = "System is going to shut down at \(Date())\n"
}
}
}
loaded the agent, and tried to restart device, I can't see as it is coming to handleNotification
Same code is working fine from sample application but not from launchAgent
Is there any restriction is there for NSWorkspace, if is that so, how to track shutdown/restart event from launchAgent or LaunchDaemon
Any help will be appreciate
Years ago my daemon was since then using SCDynamicStoreCopyConsoleUser() function and now it longer works.
Basically the daemon needs to know the user name of who is using the system. If I restart the daemon,after the login, it gets the user name.
I tried run a shell command via my daemon ("id -F") and look likes it still picks the root as user name.
So, is there a way to get the current user name using Swift? ProcessInfo.userName fails too
Hi, I work on a game for iOS and the framerate decreases progressively when the debugger is attached.
Running it for 2mins, it went from 30 to 1 FPS while rendering a simple static scene.
I narrowed it down to a call to dispatch_async_f which takes longer to execute over time.
clock_t t1 = clock();
dispatch_async_f(queue, context, function);
clock_t t2 = clock();
double duration = (double)(t2 -t1)/(double)CLOCKS_PER_SEC;
Dodumentation says dispatch_async_f is supposed to return immediatly.
So what could explain duration to increases in debug? Am i measuring this incorrectly?
The game is written in mixed C++ and ObjC. It uses Metal as graphic API and GCD for dispatching jobs.
I have Xcode 13.4.1 and test on an iPhone 13 Pro with iOS 15.7.
Thanks.
I'm needing the ability in my app (not a public app, but for an in-house private app) to
launch a third-party app
collect user inputs (like button presses, etc) (don't think this is possible)
when done with the third-party app, return to my app with the "results" of the third-party app.
My research on this topic is mixed, but am looking for clarification if this is possible.
For (1), I know I can launch another app.
For (2), I don't think this is possible, but want to confirm
For (3), I think the only way this can be done is to (while in the other app) export the data to a shared location, then tab out and select our app to resume. I could tie into the lifecycle to detect when our app resumes then scan the shared location for the results.
How and why does the dispatchgroup.notify method get called before all the entered instances have left?
I tried adding the dispatchGroup.enter within the same loop and the output is the same.
Hello,
My App is getting a Fence hang right after install in a specific scenario.
Issue1: I attempted to follow the directions, tried to symbolicate the file etc. however did not have much luck.
I was able to pinpoint the lines of code where the hang seems to occur. I did this using simple print and comment out/uncomment blocks of code related to the specific scenario. I was able to do so as, not much is happening on the Main thread in this scenario .
Issue 2: The following lines of code ( modified var etc. ) seem to cause the hang. Commenting them out gets rid of the hang across devices, while online/offline etc. I am not sure if I need to use a framework other than AVFoundation.
Note:
The file extension is mpg
The music files are static ( included in the Bundle ) and not accessed from user's playlist etc.
import
var plyr : AVAudioPlayer?
let pth = Bundle.main.path(forResource: "MusicFileName", ofType: "mpg")!
let url = URL(fileURLWithPath: pth)
do [{](https://www.example.com/)
plyr = try AVAudioPlayer(contentsOf: url)
plyr?.prepareToPlay()
plyr?.play()
} catch {
// print error etc.
}
Thanks in advance.
I would appreciate some help! Close to submission :)
Hi, I noticed in this page, there is no explanation about who/when/how the method handle_checkbox_toggle is called.
Page:
https://developer.apple.com/documentation/servicemanagement/updating-helper-executables-from-earlier-versions-of-macos?language=objc
Ultimately, how should the app come to know when a app service is allowed or disallowed in System Settings > Login Items ?
I have an ESF Client process, and this process handles AUTH event in one multi-thread, at this time, if the Client process exits abnormally, will the AUTH event not be handled, thus causing the system to freeze
我创建了一个macos 应用,应用开启了沙盒功能,我有一个shll脚本和一个嵌入的可执行命令行工具位于/Users/Library/Containers/com.***/Data/Library/Application Support/***/下面,用于拷贝工作,我发现我并不能执行成功,总是被拒绝,有人知道原因吗,
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!
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.
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.
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.
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
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?