General:
Forums subtopic: Privacy & Security > General
Forums tag: App Sandbox
App Sandbox documentation
App Sandbox Design Guide documentation — This is no longer available from Apple. There’s still some info in there that isn’t covered by the current docs but, with the latest updates, it’s pretty minimal (r. 110052019). Still, if you’re curious, you can consult an old copy [1].
App Sandbox Temporary Exception Entitlements archived documentation — To better understand the role of temporary exception entitlements, see this post.
Embedding a command-line tool in a sandboxed app documentation
Discovering and diagnosing App Sandbox violations (replaces the Viewing Sandbox Violation Reports forums post)
Resolving App Sandbox Inheritance Problems forums post
The Case for Sandboxing a Directly Distributed App forums post
Implementing Script Attachment in a Sandboxed App forums post
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] For example, this one archived by the Wayback Machine.
App Sandbox
RSS for tagApp Sandbox is a macOS access control technology designed to contain damage to the system and user data if an app becomes compromised.
Posts under App Sandbox tag
105 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
In FileProvider framework based app, is it mandatory to make the host-app sandboxed? I think, no, as Google Drive app is non-sandboxed.
But when removing sandboxing from my hostApp, even though mount is visible in Finder but extesnion is not being launched and Finder shows a error message saying "MyApp encountered an error. Items may be out of date."
And when I add app-sanboxing, then things work fine.
Can someone please help how can we remove sandboxing of hostApp and still make it work. Is there any specific entitlement we need to add, or any whitelisting needed for our Developer Team Id?
I'm trying to distribute a sandboxed macOS app with a PacketTunnelProvider (system extension) via direct distribution (outside of AppStore).
The app and the extension both use the same app group, using the new group.com.XXXX.YYYY format detailed here for 10.15+
https://developer.apple.com/forums/thread/721701
I've also followed the instructions below to get around the quirk of not being able to directly process it via XCode:
https://developer.apple.com/forums/thread/737894
I've re-signed with Developer ID certificate, all that is smooth and successfully notarized.
However upon running the app I get:
"My.app" would like to access data from other apps.
Checking
~/Library/Containers
~/Library/Group Containers
I see the correct files folders have been created before I select Don't Allow and Allow.
My app does not access any files or folders outside of the sandboxed directories.
How can I prevent this from happening?
In order to diagnose further, how to diagnose exactly which files/folder the app is trying to access that is causing this problem?
Topic:
App & System Services
SubTopic:
Networking
Tags:
Network Extension
System Extensions
App Sandbox
Developer ID
I have built an app that does audio analysis. I have stripped the GPL files from these binaries regarding license issues. The binnaries are in the root folder of ny build next to the .app file MacOs/
I can not run this in sandbox mode. Everything works except for the audio analysis. Can I still submit this to the AppStore and get accepted? Will users whom download the app be able to run the audio analysis?
I aaked this on Apple support but they gave me a general answer to appstore documentation
Hope someone here has experience with this.
Hello,
Unable to see the App Sandbox entitlement while creating a new App ID. Have tried to recreate APP ID multiple times. Don't see the option in Developer portal.
Dear Apple:
We are developing a file management-related app, I want to configure com.apple.security.temporary-exception.files.absolute-path.read-write to /Users/*** in the entitlements. Will this affect the approval process of our app on the App Store?
Script attachment enables advanced users to create powerful workflows that start in your app. NSUserScriptTask lets you implement script attachment even if your app is sandboxed. This post explains how to set that up.
IMPORTANT Most sandboxed apps are sandboxed because they ship on the Mac App Store [1]. While I don’t work for App Review, and thus can’t make definitive statements on their behalf, I want to be clear that NSUserScriptTask is intended to be used to implement script attachment, not as a general-purpose sandbox bypass mechanism.
If you have questions or comments, please put them in a new thread. Place it in the Privacy & Security > General subtopic, and tag it with App Sandbox.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] Most but not all. There are good reasons to sandbox your app even if you distribute it directly. See The Case for Sandboxing a Directly Distributed App.
Implementing Script Attachment in a Sandboxed App
Some apps support script attachment, that is, they allow a user to configure the app to run a script when a particular event occurs. For example:
A productivity app might let a user automate repetitive tasks by configuring a toolbar button to run a script.
A mail client might let a user add a script that processes incoming mail.
When adding script attachment to your app, consider whether your scripting mechanism is internal or external:
An internal script is one that only affects the state of the app.
A user script is one that operates as the user, that is, it can change the state of other apps or the system as a whole.
Supporting user scripts in a sandboxed app is a conundrum. The App Sandbox prevents your app from changing the state of other apps, but that’s exactly what your app needs to do to support user scripts.
NSUserScriptTask resolves this conundrum. Use it to run scripts that the user has placed in your app’s Script folder. Because these scripts were specifically installed by the user, their presence indicates user intent and the system runs them outside of your app’s sandbox.
Provide easy access to your app’s Script folder
Your application’s Scripts folder is hidden within ~/Library. To make it easier for the user to add scripts, add a button or menu item that uses NSWorkspace to show it in the Finder:
let scriptsDir = try FileManager.default.url(for: .applicationScriptsDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
NSWorkspace.shared.activateFileViewerSelecting([scriptsDir])
Enumerate the available scripts
To show a list of scripts to the user, enumerate the Scripts folder:
let scriptsDir = try FileManager.default.url(for: .applicationScriptsDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let scriptURLs = try FileManager.default.contentsOfDirectory(at: scriptsDir, includingPropertiesForKeys: [.localizedNameKey])
let scriptNames = try scriptURLs.map { url in
return try url.resourceValues(forKeys: [.localizedNameKey]).localizedName!
}
This uses .localizedNameKey to get the name to display to the user. This takes care of various edge cases, for example, it removes the file name extension if it’s hidden.
Run a script
To run a script, instantiate an NSUserScriptTask object and call its execute() method:
let script = try NSUserScriptTask(url: url)
try await script.execute()
Run a script with arguments
NSUserScriptTask has three subclasses that support additional functionality depending on the type of the script.
Use the NSUserUnixTask subsclass to run a Unix script and:
Supply command-line arguments.
Connect pipes to stdin, stdout, and stderr.
Get the termination status.
Use the NSUserAppleScriptTask subclass to run an AppleScript, executing either the run handler or a custom Apple event.
Use the NSUserAutomatorTask subclass to run an Automator workflow, supplying an optional input.
To determine what type of script you have, try casting it to each of the subclasses:
let script: NSUserScriptTask = …
switch script {
case let script as NSUserUnixTask:
… use Unix-specific functionality …
case let script as NSUserAppleScriptTask:
… use AppleScript-specific functionality …
case let script as NSUserAutomatorTask:
… use Automatic-specific functionality …
default:
… use generic functionality …
}
Hello 👋
Our team added com.apple.security.temporary-exception.apple-events: com.apple.Terminal recently to our Mac app to be able to tell the terminal to execute a specific command line automatically for the user when clicking a button but we've been rejected during review because of this entitlement so for now we've deleted it and deleted the associated feature.
It concerns the following feature (see attachment).
Context:
Among other things the application enable to review pull request changes (remote) and we would like a button to automatically clone the pull request on disk when user click a button. We would like to use terminal for security reason as when cloning using git command we need ssh keys or other credential and there's no reason (rather than technical ones) that the user provide us such private information that is stored in the ~/.ssh. We prefer think the other way around and tell the user what to execute instead (no credentials involved or shared).
We referred to: https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/AppSandboxTemporaryExceptionEntitlements.html
I admit it's unclear for me if this will imply a 100% rejection or if these entitlements are deprecated.
Is "com.apple.security.temporary-exception.apple-events: com.apple.Terminal" an entitlement that is reserved for special Apple partners ?
Is it an entitlement that we should demonstrate usage first ? Or should we completely remove the feature if we distribute through the App Store ?
Is Apple advice for other APIs to develop such features (execute command line for the user) when distributing through the App Store ?
As said we've disabled the feature for now.
Thank you in advance for those who will take time to answer this,
This was working a few days ago, but it has since stopped and I can't figure out why. I've tried resetting TCC, double-checking my entitlements, restarting, deleting and rebuilding, and nothing works.
My app is a sandboxed macOS SwiftUI LSUIElement app that, when invoked, checks to see if the frontmost process is Terminal, then tries to get the frontmost window’s title.
func
getFrontmostWindowTitle()
throws
-> String?
{
let trusted = AXIsProcessTrusted()
print("getFrontmostWindowTitle AX trusted: \(trusted)")
guard let app = NSWorkspace.shared.frontmostApplication else { return nil }
let appElement = AXUIElementCreateApplication(app.processIdentifier)
var focusedWindow: AnyObject?
let status = AXUIElementCopyAttributeValue(appElement, kAXFocusedWindowAttribute as CFString, &focusedWindow)
guard
status == .success,
let window = focusedWindow
else
{
if status == .cannotComplete
{
throw Errors.needAccessibilityPermission
}
return nil
}
var title: AnyObject?
let titleStatus = AXUIElementCopyAttributeValue(window as! AXUIElement, kAXTitleAttribute as CFString, &title)
guard titleStatus == .success else { return nil }
return title as? String
}
I recently renamed the app, but the Bundle ID has not yet changed. I have com.apple.security.accessibility set to YES in the Entitlements file (although i had to add it manually), and a NSAccessibilityUsageDescription string set in Info.plist.
The first time I ran this, macOS nicely prompted for permission. Now it won't do that, even when I use AXIsProcessTrustedWithOptions() to try to force it.
If I use tccutil to reset accessibility and apple events, it still doesn't prompt. If I drag my app from the build products folder to System Settings, it gets added to the system TCC DB (not the user DB). It shows an auth value of 2 for my app:
% sudo sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT client,auth_value FROM access WHERE service='kTCCServiceAccessibility' OR service='kTCCServiceAppleEvents';"
com.latencyzero.<redacted>|2
<redactd>
I'm at a loss as to what went wrong. I proved out the concept earlier and it worked, and have since spent a lot of time enhancing and polishing the app, and now things aren't working and I'm starting to worry.
We're interested in adopting App Sandbox in an app distributed outside of the Mac App Store. However, we're hitting a bit of a roadblock and it doesn't seem like either of the techniques described in that post can be used in a reasonable way.
For background, this is a third-party launcher for a cross-platform Java game that, among other things, makes it easier for users to mod the game. Users generally download mods as .jar files and place them in a certain directory. In some cases, these mods contain native dynamic libraries (e.g. a .dylib) as part of their code. In general, the .dylib is extracted from the contents of the .jar to some temporary location, loaded, and then deleted once the game closes (the exact details, like the actual temporary location, depends on the mod).
App Sandbox greatly interests us in this case because it can limit the damage that a compromised mod could do, and in my testing the functionality of most mods still works with it enabled. However, sandboxed apps quarantine every file they write to by default. Unfortunately, most mods are created by individual developers who don't notarize their libraries (their mods are generally cross-platform, and they're likely just using third-party code that they bundle with the mod but don't sign or notarize). [1] This means that a mod that loads a dynamic library as described above triggers Gatekeeper as described in the documentation if the app is sandboxed, but does not if the sandbox is disabled.
Even worse, a user often can't bypass the warning even if they trust the mod because the extracted library is usually a temporary file, and generally is deleted after the failure (which usually causes the game to crash and thus close). By the time they try to approve the code in System Settings, the file is gone (and even if they could approve it, this approval wouldn't stick next time they launch the game).
In theory it would work to use an unsandboxed XPC service to remove the quarantine and let the libraries through. However, this is easier said than done. We don't control the mods' code or how they go about loading whatever code they need, which limits what we can do.
[1] And in some cases, people like to play old versions of the game with old mods, and the versions they're using might've been released before notarization was even a thing.
The closest thing I can think of to a solution is injecting code into the Java process that runs code to call out to the XPC service to remove the quarantine before a library loads (e.g. before any calls to dlopen using dyld interposition). A prototype I have... works... but this seems really flimsy, I've read that interposition isn't meant to be used in non-dev tools, and if there's a better solution I'd certainly prefer that over this.
Other things we've tried have significant downsides:
com.apple.security.files.user-selected.executable requires user selection in a file picker, and seems to be more blunt than just allowing libraries/plugins which might lead to a sandbox escape [2]
Adding the app to the "Developer Tools" section in System Settings > Privacy & Security allows the libraries to load automatically, but requires users to add the app manually and also sounds like it would make a sandbox escape very easy [2]
Oh, and I also submitted an enhancement request for an entitlement/similar that would allow these libraries to load (FB13795828) but it was returned as "no plans to address" (which honestly wasn't that surprising).
[2] My understanding is that if a sandboxed process loads libraries, the library code would still be confined by the sandbox because it's still running in the sandboxed process. But if a sandboxed process can write and open a non-quarantined app, that app would not be within the confines of the sandbox. So basically we want to somehow allow the libraries to load but not allow standalone executables to run outside the sandbox.
In general the game and almost all popular mods I've tested work with App Sandbox enabled, except for this Gatekeeper snag. It would be a shame to completely abandon App Sandbox for this reason if everything else can be made to work.
This situation seems not super common, but documentation does say
When your sandboxed app launches for the first time, macOS creates a sandbox container on the file system (in ~/Library/Containers) and associates it with your app. Your app has full read and write access to its sandbox container, and can run programs located there as well.
which leaves me wondering whether the Gatekeeper prompt is even intended behavior since the libraries are in the sandbox container and written by the app. (By the way, my testing of the claim that apps can run programs in their sandbox container didn't seem to confirm what the documentation said, even without quarantine - FB15963761). Though, given the other documentation page I linked above which more directly references Gatekeeper and quarantined plug-ins, I doubt this is a bug.
I suppose the final question is, is this just a situation where App Sandbox won't work (at least in any supported way)? Or is there perhaps some technique we're missing?
Hi,
I want to detect if there is a fullscreen window on each screen.
_AXUIElementGetWindow and kAXFullscreenAttribute methods work, but I have to be in a non-sandbox environment to use them.
Is there any other way that also works? I don't think it's enough to judge if it's fullscreen by comparing the window size to the screen size, since it doesn't work on MacBook with notch, or the menu bar is set to 'auto-hide'.
Thanks.
Topic:
Accessibility & Inclusion
SubTopic:
General
Tags:
Accessibility
Mac App Store
Core Graphics
App Sandbox
Has anyone here encountered this? It's driving me crazy.
It appears on launch.
App Sandbox is enabled.
The proper entitlement is selected (com.apple.security.files.user-selected.read-write)
I believe this is causing an issue with app functionality for users on different machines.
There is zero documentation across the internet on this problem.
I am on macOS 26 beta. This error appears in both Xcode and Xcode-beta.
Please help!
Thank you,
Logan
Hi everyone,
We’re developing a macOS SwiftUI app that uses a local Swift Package (CasSherpaCore) to invoke an external compiled binary (sherpa-onnx-offline-tts) for text-to-speech synthesis using system calls. The package works flawlessly when tested from terminal or via a lightweight test C program.
However, when we invoke it from a SwiftUI app (even with Full Disk Access granted to Xcode and Terminal), we consistently get the error:
sh: /Users/xxxxxxxxxxx/SherpaONNX/sherpa-onnx/build/bin/sherpa-onnx-offline-tts: Operation not permitted
We’ve tried:
Granting Full Disk Access to Xcode and Terminal.
Removing the quarantine flag with xattr -d com.apple.quarantine.
Setting executable permission via chmod +x.
Using both system() and Process in C and Swift contexts.
Testing within a Swift Package that’s integrated into the app as a local dependency.
Running the command manually from terminal (works perfectly).
It appears that macOS (or Xcode’s runtime sandbox) is restricting execution of binaries from certain locations or contexts when launched via system() inside the app.
Questions:
Is there a specific entitlement or configuration that allows execution of local binaries from a SwiftUI macOS app?
Is this related to System Integrity Protection (SIP) or a hardened runtime limitation?
Are there best practices or alternative approaches to safely execute local TTS binaries from within a Swift app?
Any help would be deeply appreciated. This is a core feature in our project and we’re stuck at this point. Thank you so much in advance!
I've developed a Mac app distributed through the App Store that uses NSAppleScript to control Spotify and Apple Music. I'm experiencing inconsistent behavior with automation permission prompts that's affecting user experience.
Expected Behavior:
When my app first attempts to send Apple Events to Spotify or Apple Music, macOS should display the automation permission prompt, and upon user approval, the app should appear in System Preferences > Security & Privacy > Privacy > Automation.
Actual Behavior:
Initial permission prompts work correctly when both apps are actively used after my app download. If a user hasn't launched Spotify/Apple Music for an extended period, the permission prompt fails to appear when they later open the music app. The music app doesn't appear in the Automation privacy pane too. Once this happens, permission prompts never trigger again for that app
Steps to Reproduce:
Fresh install of my app
Don't use Spotify for several days/weeks
Launch Spotify
Trigger Apple Events from my app to Spotify
No permission prompt appears, app doesn't show in Automation settings
If you're using Apple Music during this time it runs without any problems.
Troubleshooting Attempted:
Used tccutil reset AppleEvents [bundle-identifier] - no effect
Verified target apps are fully launched before sending Apple Events
Tried different AppleScript commands to trigger permissions
Problem occurs inconsistently across different Macs
Technical Details:
macOS 13+ support
Using standard NSAppleScript with simple commands like "tell application 'Spotify' to playpause"
App Store distribution (no private APIs)
Issue affects both Spotify and Apple Music but seems more prevalent with Apple Music
Questions:
Is there a reliable way to programmatically trigger the automation permission prompt?
Are there timing dependencies for when macOS decides to show permission prompts?
Could app priority/usage patterns affect permission prompt behavior?
I use MediaManager to run the functions and initialize it on AppDidFinishLaunching method and start monitoring there.
Any insights or workarounds would be greatly appreciated. This inconsistency is affecting user onboarding and app functionality.
Dear Apple developers:
Hello, recently I want to develop an application for macos that automatically switches input methods. The function is that when you switch applications, it can automatically switch to the input method you set, thus eliminating the trouble of manual switching.
All the functions have been implemented, but only when the sandbox is closed. When I opened the sandbox, I found a very strange phenomenon. Suppose wechat was set to the Chinese input method. When I switched to wechat, wechat automatically got the focus of the input box. The input method icon in the upper right corner of the screen had actually switched successfully, but when I actually input, it was still the previous input method. If you switch to an application that does not have a built-in focus, the automatic switching of the input method will take effect when you click the input box with the mouse to regain the focus. This phenomenon is too difficult for my current technical level.
I have tried many methods but none of them worked. I hope the respected experts can offer some ideas. Below is a snippet of the code switching I provided:
DispatchQueue. Main. AsyncAfter (deadline: now () + 0.1) {
let result = TISSelectInputSource(inputSource)
if result == noErr {
print(" Successfully switched to input method: \(targetInputMethod)")
} else {
print(" Input method switch failed. Error code: \(result)")
}
// Verify the switching result
if let newInputSource = getCurrentInputSource() {
print(" Switched input method: (newInputSource)")
}
}
When the sandbox is opened, the synchronous switching does not take effect. The input method icon in the status bar will flash for a moment, unable to compete with system events. Even if it is set to DispatchQueue.main.async, it still does not work. It seems that there is a timing issue with the input method switching.
Development environment
macOS version: 15.4.1
Xcode version: 16.2
We are unable to programmatically enable AppleScript automation for VoiceOver on macOS 15 (Sequoia)
In macOS 15, Apple moved the VoiceOver configuration from:
~/Library/Preferences/com.apple.VoiceOver4/default.plist
to a sandboxed path:
~/Library/Group Containers/group.com.apple.VoiceOver/Library/Preferences/com.apple.VoiceOver4/default.plist
Steps to Reproduce:
Use a macOS 15 (ARM64) machine (or GitHub Actions runner image with macOS 15 ARM).
Open VoiceOver:
open /System/Library/CoreServices/VoiceOver.app
Set the SCREnableAppleScript flag to true in the new sandboxed .plist:
plutil -replace SCREnableAppleScript -bool true ~/Library/Group\ Containers/group.com.apple.VoiceOver/Library/Preferences/com.apple.VoiceOver4/default.plist
Confirm csrutil status is either disabled or not enforced.
Attempt to control VoiceOver via AppleScript (e.g., using osascript voiceOverPerform.applescript).
Observe that the AppleScript command fails with no useful output (exit code 1), and VoiceOver does not respond to automation.
Topic:
Accessibility & Inclusion
SubTopic:
General
Tags:
macOS
Accessibility
App Sandbox
AppleScript
Hello!
My question is about 1) if we can use any and or all accessibility features within a sandboxed app and 2) what steps we need to take to do so.
Using accessibility permissions, my app was working fine in Xcode. It used NSEvent.addGlobalMonitorForEvents and localMoniter, along with CGEvent.tapCreate. However, after downloading the same app from the App Store, the code was not working. I believe this was due to differences in how permissions for accessibility are managed in Xcode compared to production.
Is it possible for my app to get access to all accessibility features, while being distributed on the App Store though? Do I need to add / request any special entitlements like com.apple.security.accessibility?
Thanks so much for the help. I have done a lot of research on this online but found some conflicting information, so wanted to post here for a clear answer.
Hello everyone,
I'm a new developer who just finished building my app. I'm now preparing to submit it to the App Store but wanted to beta-test it first via TestFlight.
During the upload process, I encountered an error prompting me to add sandbox entitlements, which I did. The app successfully made it to TestFlight, and I invited myself and a few fellow developers to test it. However, we're running into an issue:
On first launch, the app displays a popup directing users to Privacy & Security > Accessibility to grant permissions.
The sandboxed version does not show the app as a toggle in Accessibility settings.
Manually adding the app via the + button and selecting it directly doesn’t seem to resolve the permission issue.
I understand that I may need additional entitlements depending on the app's functionality, but I'm unsure which ones are required. Specifically:
Which entitlement controls whether the app appears in Accessibility settings?
Additionally:
How can I test these permission workflows locally (without re-uploading to TestFlight) to verify fixes before resubmitting?
Any guidance on debugging this—whether related to entitlements, sandboxing, or local testing—would be greatly appreciated!
Thanks in advance.
Despite signing out of my sandbox Apple ID and disabling Developer Mode, my Wallet still appears to be in sandbox mode, and I’m unable to add any real payment cards.
I have already tried the following steps:
Signed out of all sandbox and developer accounts
Turned off Developer Mode
Restarted the device
Reset all settings
Updated to the latest iOS version
Removed any configuration profiles
Unfortunately, none of these actions helped. The Wallet interface still displays “sandbox” and rejects real cards.
Hello, I want to access the Docker socket API from inside the macOS App Sandbox. The method queries the API using curl with --unix-socket. However, the Sandbox blocks the request, as shown by the log: curl(22299) deny(1) network-outbound /Users/user/.docker/run/docker.sock Outgoing network traffic is generally allowed, but access to the Docker Unix socket is denied.
Here’s the code I’m using:
private func executeDockerAPI() -> String {
let process = Process()
let pipe = Pipe()
process.executableURL = URL(fileURLWithPath: "/usr/bin/curl")
process.arguments = [
"--unix-socket", "/Users/user/.docker/run/docker.sock",
"http://127.0.0.1/containers/json"
]
process.standardOutput = pipe
process.standardError = pipe
do {
try process.run()
process.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8) {
return output
} else {
return "Error while decoding"
}
} catch {
return "Error running command: \(error.localizedDescription)"
}
}
Is there any entitlement or sandbox configuration I’m missing to allow access to /Users/user/.docker/run/docker.sock from inside the sandbox?
Hello everyone,
I'm developing a macOS application that programmatically sets custom icons for folders, and I've hit a wall trying to get Finder to display the icon changes consistently.
The Goal:
To change a folder's icon using NSWorkspace.shared.setIcon and have Finder immediately show the new icon.
What I've Tried (The Refresh Mechanism):
After setting the icon, I attempt to force a Finder refresh using several sandbox-friendly techniques:
Updating the Modification Date (the "touch" method):
try FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: pathToUse)
Notifying NSWorkspace:
NSWorkspace.shared.noteFileSystemChanged(pathToUse)
Posting Distributed Notifications:
DistributedNotificationCenter.default().post(name: Notification.Name("com.apple.Finder.FolderChanged"), object: pathToUse)
The Problem:
This combination of methods works perfectly, but only under specific conditions:
When setting a custom icon on a folder for the first time.
When changing the icon of an alias.
For any subsequent icon change on a regular folder, Finder stubbornly displays the old, cached icon. I've confirmed that the user can see the new icon by manually closing and reopening the folder window, but this is obviously not a user-friendly solution.
Investigating a Reset with AppleScript:
I've noticed that the AppleScript update command seems to force the kind of complete refresh I need:
tell application "Finder"
update POSIX file "/path/to/your/folder"
end tell
Running this seems to reset the folder's state in Finder, effectively recreating the "first-time set" scenario where my other methods work.
However, the major roadblock is that I can't figure out how to reliably execute this from a sandboxed environment. I understand it likely requires specific scripting entitlements, but it's unclear which ones would be needed for this update command on a user-chosen folder, or if it's even permissible for the App Store.
My Questions:
Is there a reliable, sandbox-safe way to make the standard Cocoa methods (noteFileSystemChanged, updating the modification date, etc.) work for subsequent icon updates on regular folders? Am I missing a step?
If not, what is the correct way to configure a sandboxed app's entitlements to safely run the tell application "Finder" to update command for a folder the user has granted access to?
Any insight or alternative approaches would be greatly appreciated. Thank you