Foundation

RSS for tag

Access essential data types, collections, and operating-system services to define the base layer of functionality for your app using Foundation.

Posts under Foundation tag

200 Posts

Post

Replies

Boosts

Views

Activity

Networking Resources
General: Forums subtopic: App & System Services > Networking TN3151 Choosing the right networking API Networking Overview document — Despite the fact that this is in the archive, this is still really useful. TLS for App Developers forums post Choosing a Network Debugging Tool documentation WWDC 2019 Session 712 Advances in Networking, Part 1 — This explains the concept of constrained networking, which is Apple’s preferred solution to questions like How do I check whether I’m on Wi-Fi? TN3135 Low-level networking on watchOS TN3179 Understanding local network privacy Adapt to changing network conditions tech talk Understanding Also-Ran Connections forums post Extra-ordinary Networking forums post Foundation networking: Forums tags: Foundation, CFNetwork URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms. Network framework: Forums tag: Network Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms. Building a custom peer-to-peer protocol sample code (aka TicTacToe) Implementing netcat with Network Framework sample code (aka nwcat) Configuring a Wi-Fi accessory to join a network sample code Moving from Multipeer Connectivity to Network Framework forums post Network Extension (including Wi-Fi on iOS): See Network Extension Resources Wi-Fi Fundamentals TN3111 iOS Wi-Fi API overview Wi-Fi Aware framework documentation Wi-Fi on macOS: Forums tag: Core WLAN Core WLAN framework documentation Wi-Fi Fundamentals Secure networking: Forums tags: Security Apple Platform Security support document Preventing Insecure Network Connections documentation — This is all about App Transport Security (ATS). Available trusted root certificates for Apple operating systems support article Requirements for trusted certificates in iOS 13 and macOS 10.15 support article About upcoming limits on trusted certificates support article Apple’s Certificate Transparency policy support article What’s new for enterprise in iOS 18 support article — This discusses new key usage requirements. Technote 2232 HTTPS Server Trust Evaluation Technote 2326 Creating Certificates for TLS Testing QA1948 HTTPS and Test Servers Miscellaneous: More network-related forums tags: 5G, QUIC, Bonjour On FTP forums post Using the Multicast Networking Additional Capability forums post Investigating Network Latency Problems forums post WirelessInsights framework documentation iOS Network Signal Strength Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
3.4k
Aug ’25
Recursively walk a directory using File Coordination
What’s the recommended way to recursively walk through a directory tree using File Coordination? From what I understand, coordinating a read of a directory only performs a “shallow” lock; this would mean that I’d need to implement the recursive walk myself rather than use FileManager.enumerator(at:includingPropertiesForKeys:options:errorHandler:) plus a single NSFileCoordinator.coordinate(with:queue:byAccessor:) call. I’m trying to extract information from all files of a particular type, so I think using NSFileCoordinator.ReadingOptions.immediatelyAvailableMetadataOnly on each file before acquiring a full read lock on it (if it’s the right file type) would make sense. Am I on the right track?
5
0
92
17h
How to detect or opt out of iOS app prewarming?
Hi, We are running into issues with iOS app prewarming, where the system launches our app before the user has entered their passcode. In our case, the app stores flags, counters, and session data in UserDefaults and the Keychain. During prewarm launches: UserDefaults only returns default values (nil, 0, false). We have no way of knowing whether this information is valid or just a placeholder caused by prewarming. Keychain items with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly are inaccessible, which can lead to broken business logic (the app can assume no session exists). No special launch options or environment variables appear to be set. We can reproduce this 100% of the time by starting a Live Activity in the app before reboot. Here’s an example of the workaround we tried, following older recommendations: __attribute__((constructor)) static void ModuleInitializer(void) { char* isPrewarm = getenv("ActivePrewarm"); if (isPrewarm != NULL && isPrewarm[0] == '1') { exit(0); // prevent prewarm launch from proceeding } } On iOS 16+, the ActivePrewarm environment variable doesn’t seem to exist anymore (though older docs and SDKs such as Sentry reference it). We also tried listening for UIApplication.protectedDataDidBecomeAvailableNotification, but this is not specific to prewarming (it also fires when the device gets unlocked) and can cause watchdog termination if we delay work too long. Questions: Is there a supported way to opt out of app prewarming? What is the correct way to detect when an app is being prewarmed? Is the ActivePrewarm environment variable still supported in iOS 16+? Ideally, the UserDefaults API itself should indicate whether it is returning valid stored values or defaults due to the app being launched in a prewarm session. We understand opting out may impact performance, but data security and integrity are our priority. Any guidance would be greatly appreciated.
1
0
98
20h
[iOS 26] Unable to start TLS handshake connection to devices with self-signed certificates
Hi there, We are facing some issues regarding TLS connectivity: Starting with iOS 26, the operating system refuses to open TLS sockets to local devices with self-signed certificates over Wi-Fi. In this situation, connection is no longer possible, even if the device is detected on the network with Bonjour. We have not found a workaround for this problem. We've tryied those solutions without success: Added the 'NSAppTransportSecurity' key to the info.plist file, testing all its items, such as "NSAllowsLocalNetworking", "NSExceptionDomains", etc. Various code changes to use properties such as "sec_protocol_options_set_local_identity" and "sec_protocol_options_set_tls_server_name" to no avail. Brutally import the certificate files into the project and load them via, for example, "Bundle.main.url(forResource: "nice_INTERFACE_server_cert", withExtension: "crt")", using methods such as sec_trust_copy_ref and SecCertificateCopyData. Download the .pem or .crt files to the iPhone, install them (now visible under "VPN & Device Management"), and then flag them as trusted by going to "Settings -> General -> Info -> Trust". certificates" The most critical part seems to be the line sec_protocol_options_set_verify_block(tlsOptions.securityProtocolOptions, { $2(true) }, queue) whose purpose is to bypass certificate checks and validate all of them (as apps already do). However, on iOS26, if I set a breakpoint on leg$2(true),` it never gets there, while on iOS 18, it does. I'll leave as example the part of the code that was tested the most below. Currently, on iOS26, the handler systematically falls back to .cancelled: func startConnection(host: String, port: UInt16) { self.queue = DispatchQueue(label: "socketQueue") let tlsOptions = NWProtocolTLS.Options() sec_protocol_options_set_verify_block(tlsOptions.securityProtocolOptions, { $2(true) }, queue) let parameters = NWParameters(tls: tlsOptions) self.nwConnection = NWConnection(host: .init(host), port: .init(rawValue: port)!, using: parameters) self.nwConnection.stateUpdateHandler = { [weak self] state in switch state { case .setup: break case .waiting(let error): self?.connectionDidFail(error: error) case .preparing: break case .ready: self?.didConnectSubject.onNext(Void()) case .failed(let error): self?.connectionDidFail(error: error) case .cancelled: self?.didDisconnectSubject.onNext(nil) @unknown default: break } } self.setupReceive() self.nwConnection.start(queue: queue) } These are the prints made during the procedure. The ones with the dot are from the app, while the ones without are warnings/info from Xcode: 🔵 INFO WifiNetworkManager.connect():52 - Try to connect onto the interface access point with ssid NiceProView4A9151_AP 🔵 INFO WifiNetworkManager.connect():68 - Connected to NiceProView4A9151_AP tcp_output [C13:2] flags=[R.] seq=215593821, ack=430284980, win=4096 state=CLOSED rcv_nxt=430284980, snd_una=215593821 nw_endpoint_flow_failed_with_error [C13 192.168.0.1:443 in_progress channel-flow (satisfied (Path is satisfied), viable, interface: en0[802.11], dns, uses wifi, LQM: unknown)] already failing, returning nw_connection_copy_protocol_metadata_internal_block_invoke [C13] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection nw_connection_copy_protocol_metadata_internal_block_invoke [C13] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection nw_connection_copy_connected_local_endpoint_block_invoke [C13] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection nw_connection_copy_connected_remote_endpoint_block_invoke [C13] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection nw_connection_copy_protocol_metadata_internal_block_invoke [C14] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection nw_connection_copy_protocol_metadata_internal_block_invoke [C14] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection nw_connection_copy_connected_local_endpoint_block_invoke [C14] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection nw_connection_copy_connected_remote_endpoint_block_invoke [C14] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection [C14 192.168.0.1:443 tcp, tls, attribution: developer] is already cancelled, ignoring cancel [C14 192.168.0.1:443 tcp, tls, attribution: developer] is already cancelled, ignoring cancel nw_connection_copy_protocol_metadata_internal_block_invoke [C15] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection nw_connection_copy_protocol_metadata_internal_block_invoke [C15] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection nw_connection_copy_connected_local_endpoint_block_invoke [C15] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection nw_connection_copy_connected_remote_endpoint_block_invoke [C15] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection nw_connection_copy_protocol_metadata_internal_block_invoke [C16] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection nw_connection_copy_protocol_metadata_internal_block_invoke [C16] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection nw_connection_copy_connected_local_endpoint_block_invoke [C16] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection nw_connection_copy_connected_remote_endpoint_block_invoke [C16] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection [C16 192.168.0.1:443 tcp, tls, attribution: developer] is already cancelled, ignoring cancel [C16 192.168.0.1:443 tcp, tls, attribution: developer] is already cancelled, ignoring cancel 🔴 ERROR InterfaceDisconnectedViewModel.connect():51 - Sequence timeout.
1
0
50
1d
Calendar's date func is not behaving as I'd expect...
When I run this in a playground: var meDate = Calendar.current.date(from: DateComponents(year: 2024, hour: 7, weekday: 3, weekdayOrdinal: 2))! print(meDate) I see: 2024-01-09 15:00:00 +0000 This seems correct to me. jan 9th is the second Tuesday in 2024 I'm in the pacific TZ, 07:00 PDT matches 15:00GMT But then I do this: meDate = Calendar.current.date(bySetting: .weekday, value: 4, of: meDate)! print(meDate) and I see: 2024-01-10 08:00:00 +0000 I would have expected my hour value (7PST/15GMT) to have been preserved. Is there a way I can update weekday, but not lose my hour?
2
0
326
3d
Questions about using App Extension communication with host apps on iOS 26 (Xcode 26)
Hello, I have a few questions regarding the documentation here: Can this method described in the article be built with Xcode 26 and run on iOS 26? Or is it restricted to run only on iOS 26, since AppExtensionPoint appears to be available starting from iOS 26? Does this approach allow two apps under the same Team ID to communicate with each other? Does this approach also allow two apps under different Team IDs to communicate with each other? Is it mandatory to implement EXAppExtensionBrowserViewController and obtain user consent before using this method to exchange information? In our implementation, we followed the documentation. Inside EXAppExtensionBrowserViewController, we were able to see the Generic Extension from another app and enabled the permission. However, we still get the following error: Failed to connect: Error Domain=NABUExtensionConnector Code=1 "No matching extension found" UserInfo={NSLocalizedDescription=No matching extension found} Could someone clarify whether this is expected behavior, or if we are missing an additional configuration step? Thanks in advance!
5
0
209
4d
Grammar checking is never requested
I have prepared a NSSpellServer spelling and grammar checker for Slovenian proofing in macOS. My proofing service gets used when I explicitly set keyboard spelling language to "Slovenian (Besana)" (my proofing service). However, no matter how I set the Check Grammar With Spelling option or Check Grammar checkbox in the TextEdit.app or Mail.app, my proofing service does not get any request for grammar checking. I am supporting checkString call for Unified checking and checkingTypes never contains NSTextCheckingTypeGrammar flag. When using legacy API before Unified checking support, the checkGrammarInString is never called either. If I do the grammar regardless the checkingTypes parameter, the app shows grammar mistakes correctly. But that is bad UX. Need to follow user demand for with grammar or without grammar. I don't know what am I doing wrong? On my home iMac v11 it actually works. No idea what I did there to make it work. Just worked. On my working Mac Mini v13 it won't check grammar. On another MacBook Pro v15, it won't check grammar either. Apps do check spelling with my proofing service. But not grammar. Same apps do grammar checking with stock AppleSpelling.service just fine. I have checked my Info.plist, using Hardened Runtime, have empty Entitlements, to no avail. Was there some new grammar API introduced after macOS v11 Big Sur, I should implement? Is there some specific Entitlement, signature, notarization I should perform to get going? Some documentation I am missing?
2
0
90
5d
Can't get a scoped resource URL from drag and drop
Hi, My Mac app allows a customer to drag and drop a file package onto a SwiftUI view. I can't seem to find a way to successfully call .startAccessingSecurityScopedResource() with the file/dir that was dropped into the view. I put together a simple test app. Here is the code: struct ContentView: View { @State var isTargetedForDrop: Bool = false var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") Rectangle() .stroke(Color.gray) .onDrop(of: [UTType.fileURL], isTargeted: $isTargetedForDrop) { providers in guard let provider = providers.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) }) else { return false } provider.loadItem(forTypeIdentifier: UTType.fileURL.identifier, options: nil) { item, error in if let error = error { print("Drop load error: \(error)") return } if let url = item as? URL { print("Dropped file URL: \(url)") } else if let data = item as? Data, let url = URL(dataRepresentation: data, relativeTo: nil) { print("Dropped file URL (from data): \(url)") let access = url.startAccessingSecurityScopedResource() if access { print("Successfully accessed file at URL: \(url)") } else { print("Failed to access file at URL: \(url)") } url.stopAccessingSecurityScopedResource() } else { print("Unsupported dropped item: \(String(describing: item))") } } return true } } .padding() } } When I drop a file package into this view I see, "Failed to access file at URL: <the_full_file_path>" I'm running Xcode 26 on macOS 26.
1
0
59
6d
Click on UITextView or UITextField to crash
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString timeIntervalSinceReferenceDate]: unrecognized selector sent to instance 0x115fadbc0' *** First throw call stack: (0x1940bd8c8 0x1910097c4 0x194159838 0x19403a4f8 0x1940423a0 0x1e42cb9a8 0x1e42ce220 0x106f02c08 0x1080a461c 0x1080be2b0 0x1080acb2c 0x1080ad7b4 0x1080b9b00 0x1080b91a4 0x1eecdb3b8 0x1eecda8c0) libc++abi: terminating due to uncaught exception of type NSException InputAnalytics called timeIntervalSinceReferenceDate in dispatch_sync.The display issue of the call stack occurs in two stages: keyboard input analysis and folding the keyboard.After adding protection to NSString, it can function normally, but I want to know the reason. #import "NSString+Safe.h" @implementation NSString (Safe) - (NSTimeInterval)timeIntervalSinceReferenceDate { return 0; } - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)date { return 0; } @end
3
0
74
1w
Issue when creating Bookmark with security scope on macOS 26 RC
With the RC version of macOS 26, an issue persists when you try to create a bookmark with security scope for the root folder "/". This leads to an error "The file couldn’t be opened.". However, you can create bookmark for /Applications, /System, /Users... This is quite annoying for one of my app because a user can create a cartography of his disk usage, and the access to the root folder "/" is the only way to do so! Is there a workaround? PS: reported the issue with ID FB20186406 let openPanel = NSOpenPanel() openPanel.canChooseDirectories = true openPanel.canChooseFiles = false openPanel.beginSheetModal(for: self.view.window!) { (result) in guard result == .OK, let folderURL = openPanel.url else { return } openPanel.close() do { let data = try folderURL.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil) print("Bookmark data was created for \(folderURL.path)") } catch (let error) { print("Error creating bookmark for \(folderURL.path), with error: \(error.localizedDescription)") } }
4
0
187
1w
Crash in libquic.dylib when app is backgrounded and issues an HTTP/3 request on iOS 26
Title / Summary Crash in libquic.dylib when app is backgrounded and issues an HTTP/3 request Description On iOS 26, the app crashes inside libquic.dylib while performing a network request using HTTP/3 (QUIC) after the app has moved to the background. The crash happens within low-level QUIC / libquic internals. Reproduction Steps Launch the app, perform normal operations. Background the app (press home / switch away). While in background, trigger a network request that uses HTTP/3 / QUIC. Observe that the app crashes (stack trace pointing into libquic.dylib). Expected Behavior The HTTP/3 request in background should either be handled gracefully (fail or complete) without causing a crash; the app must not be terminated due to internal libquic failures. Actual Behavior The app crashes with signals/exceptions coming from libquic.dylib (in the QUIC / packet building / encryption / key state logic) when a HTTP/3 request is made in background. Environment / Device Information • OS: iOS 26 • Device: iPhone 13 Pro Max • Network environment: (Wi-Fi / Cellular) • HTTP/3 support: enabled in URLSession / Network framework Stack Trace: 8eedc0df3d914b0faf8def9af3b21574-symbolicated.crash
2
0
95
1w
Click on UITextView or UITextField to crash
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString timeIntervalSinceReferenceDate]: unrecognized selector sent to instance 0x115fadbc0' *** First throw call stack: (0x1940bd8c8 0x1910097c4 0x194159838 0x19403a4f8 0x1940423a0 0x1e42cb9a8 0x1e42ce220 0x106f02c08 0x1080a461c 0x1080be2b0 0x1080acb2c 0x1080ad7b4 0x1080b9b00 0x1080b91a4 0x1eecdb3b8 0x1eecda8c0) libc++abi: terminating due to uncaught exception of type NSException InputAnalytics called timeIntervalSinceReferenceDate in dispatch_sync.The display issue of the call stack occurs in two stages: keyboard input analysis and folding the keyboard. After adding protection to NSString, it can function normally, but I want to know the reason #import "NSString+Safe.h" @implementation NSString (Safe) - (NSTimeInterval)timeIntervalSinceReferenceDate { return 0; } - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)date { return 0; } @end
1
0
70
1w
RTT call option and confirmation dialog missing when dialing emergency numbers
Hello, In our app we provide a button that initiates a phone call using tel://. For normal numbers, tapping the button presents the standard iOS confirmation sheet with Call and Cancel. If RTT is enabled on the device, the sheet instead shows three options: Call, Cancel, and RTT Call. However, when dialing a national emergency number, this confirmation dialog does not appear at all — the call is placed immediately, without giving the user the choice between voice or RTT. Is this the expected system behavior for emergency numbers on iOS? 
And if so, how does RTT get applied in the emergency-call flow — is it managed entirely by the OS rather than exposed as a user-facing option? Thanks in advance for clarifying.
2
0
581
1w
Language detection
I have prepared a NSSpellServer spelling and grammar checker for Slovenian proofing in macOS. My proofing service gets used when I explicitly set keyboard spelling language to "Slovenian (Besana)" (my proofing tool). When I set keyboard language to Automatic by Language, system does the language detection. Since it has limited support for Slovenian language, it doesn't recognize the text as Slovenian and never asks my proofing service to check the spelling. It does consult my proofing service for spelling suggestions and when it does, I see the language parameter there is set to anything but Slovenian. Is it possible to install own language detector to macOS? Or, place some language dictionary files somewhere, the system could use to extend language detection to new languages?
1
0
67
2w
App Store–Compliant Methods for Uninstalling Root-Owned Applications
I would like to understand the recommended App Store–compliant method for uninstalling applications, particularly in cases where certain apps are owned by root rather than the user. Currently, since root-owned apps cannot be uninstalled, I display the error message: 'App name couldn’t be moved to the Trash because you don’t have permission to access it. please run sudo chown -R $user /application/appname and try again' I then instruct users to change the ownership of the app and try again, but this approach does not appear to align with App Store policies.
5
0
82
2w
Swift Playground - Types Lesson
While I am not new to programming, I am quite new to the Swift language. I am using the Swift Playground app on macOS 26 on an M1 MacBook Air. I am on the lesson about types. Perhaps it's a silly question, but what is a portal? It is never described or pointed out where to find it in the puzzle world. Similarly, the instructions reference a "switch" object without ever defining what it is. I cannot write code to call methods or set properties on objects about which I have no useful information. Can anyone advise, please? Thank you kindly.
3
0
163
2w
What's the best way to detect if the app was installed from TestFlight (iOS & macOS)?
For ages, we've been using appStoreReceiptUrl to detect if the app was installed from TestFlight or not, but now that's deprecated. Since we have a strict policy of no warnings on the project, we need to find a way to check if the app was installed from TestFlight or from the App Store. Does anyone know what's the new way to do so? I thought about using MarketplaceKit.AppDistributor.testFlight but to use MarketplaceKit you need to jump through hoops that our app really doesn't need to - we don't distribute outside of the App Store. Any ideas are much appreciated! 🙏
0
2
154
3w
Huge timeout values from a failed DiskIO call
I have created a sample app which read/write from a network file. When the file was attempted to open (using open Linux API), connection to network file was lost. The thread which was stuck on the open method, returns after a long time. It was observed that for macOS, the maximum return time of the thread was around 10 mins, whereas in Windows and Linux, the maximum timeout was 60 sec and 90 sec. macOS has a very large timeout before returning the thread with a network failure error. Is this by designed and expected? With a large timeout as 10mins, it's difficult to respond swiftly back to the user.
7
0
207
3w
Selecting ~/Library in open panel doesn't give access to ~/Library/Mail
A user of my app brought to my attention that unless they select their ~/Library/Mail folder explicitly in an open panel, they get an error when scanning it inside my app. I can confirm that I also get a permission error when trying to scan it as a subfolder of ~/Library, but not if I select it directly. I'm assuming this is intentional, but it would be nice to have an explanation or some documentation that I can point my users to when they encounter what appears to them as a bug in my app. What makes this matter even more confusing is that selecting a folder in any open panel of an app gives the app access to it for the lifetime of the app, but after restarting the app, access is lost again (unless it has a bookmark to it). This was probably the reason why the user thought that it worked in another app but not in mine. This is the code I use to scan: let openPanel = NSOpenPanel() openPanel.canChooseDirectories = true if openPanel.runModal() == .cancel { return } let enumerator = FileManager.default.enumerator(at: openPanel.urls[0], includingPropertiesForKeys: nil) { url, error in print(url.path, error) return true } while let url = enumerator?.nextObject() as? URL { } And this the error related to the Mail folder: ~/Library/Mail Error Domain=NSCocoaErrorDomain Code=257 "The file “Mail” couldn’t be opened because you don’t have permission to view it." UserInfo={NSURL=file:///~/Library/Mail, NSFilePath=/~/Library/Mail, NSUnderlyingError=0x600002991470 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
4
0
96
3w
Helper app is sandboxed (entitlement + runtime check), but `URLsForDirectory:` returns user home (`/Users//`) instead of container path — why?
Problem summary I have a macOS helper app that is launched from a sandboxed main app. The helper: has com.apple.security.app-sandbox = true and com.apple.security.inherit = true in its entitlements, is signed and embedded inside the main app bundle (placed next to the main executable in Contents/MacOS), reports entitlement_check = 1 (code signature contains sandbox entitlement, implemented via SecStaticCode… check), sandbox_check(getpid(), NULL, 0) returns 1 (runtime sandbox enforcement present), APP_SANDBOX_CONTAINER_ID environment variable is not present (0). Despite that, Cocoa APIs return non-container home paths: NSHomeDirectory() returns /Users/&lt;me&gt;/ (the real home). [[NSFileManager defaultManager] URLsForDirectory:inDomains:] and URLForDirectory:inDomain:appropriateForURL:create:error: return paths rooted at /Users/&lt;me&gt;/ (not under ~/Library/Containers/&lt;app_id&gt;/Data/...) — i.e. they look like non-sandboxed locations. However, one important exception: URLForDirectory:... for NSItemReplacementDirectory (temporary/replacement items) does return a path under the helper's container (example: ~/Library/Containers/&lt;app_id&gt;/Data/tmp/TemporaryItems/NSIRD_&lt;helper_name&gt;_hfc1bZ). This proves the sandbox is active for some FileManager APIs, yet standard directory lookups (Application Support, Documents, Caches, and NSHomeDirectory()) are not being redirected to the container. What I expect The helper (which inherits the sandbox and is clearly sandboxed) should get container-scoped paths from Cocoa’s FileManager APIs (Application Support, Documents, Caches), i.e. paths under the helper’s container: /Users/&lt;me&gt;/Library/Containers/&lt;app_id&gt;/Data/.... What I tried / diagnostics already gathered Entitlements &amp; code signature codesign -d --entitlements :- /path/to/Helper.app/Contents/MacOS/Helper # shows com.apple.security.app-sandbox = true and com.apple.security.inherit = true Runtime checks (Objective-C++ inside helper): extern "C" int sandbox_check(pid_t pid, const char *op, int flags); NSLog(@"entitlement_check = %d", entitlement_check()); // SecStaticCode check NSLog(@"env_variable_check = %d", (getenv("APP_SANDBOX_CONTAINER_ID") != NULL)); NSLog(@"runtime_sandbox_check = %d", sandbox_check(getpid(), nullptr, 0)); NSLog(@"NSHomeDirectory = %s", NSHomeDirectory()); NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask]; NSLog(@"URLsForDirectory: %@", urls); Observed output: entitlement_check = 1 env_variable_check = 0 runtime_sandbox_check = 1 NSHomeDirectory = /Users/&lt;me&gt; URLsForDirectory: ( "file:///Users/&lt;me&gt;/Library/Application%20Support/..." ) Temporary/replacement directory (evidence sandbox active for some APIs): NSURL *tmpReplacement = [[NSFileManager defaultManager] URLForDirectory:NSItemReplacementDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&amp;err]; NSLog(@"NSItemReplacementDirectory: %@", tmpReplacement.path); Observed output (example): /Users/&lt;me&gt;/Library/Containers/&lt;app_id&gt;/Data/tmp/TemporaryItems/NSIRD_&lt;helper_name&gt;_hfc1bZ Other facts Calls to NSHomeDirectory() and URLsForDirectory: are made after main() to avoid "too early" initialization problems. Helper is placed in Contents/MacOS (not Contents/Library/LoginItems). Helper is a non-GUI helper binary launched by the main app (not an XPC service). macOS version: Sequoia 15.6 Questions Why do NSHomeDirectory() and URLsForDirectory: return the real /Users/&lt;me&gt;/... paths in a helper process that is clearly sandboxed (entitlement + runtime enforcement), while NSItemReplacementDirectory returns a container-scoped temporary path? Is this behavior related to how the helper is packaged or launched (e.g., placement in Contents/MacOS vs Contents/Library/LoginItems, or whether it is launched with posix_spawn/fork+exec vs other APIs)? Are there additional entitlements or packaging rules required for a helper that inherits sandbox to have Cocoa directory APIs redirected to the container (for Application Support, Documents, Caches)? *Thanks in advance — I can add any requested logs
6
0
92
3w