MacOs. How can I ask access for System Events on every app?

Viewed 2554

I need my Mac Swift app uses the System Events (via Applescript) to close any app that user adds to a list. I see in my System Preferences a lot of apps having System Events access in Automation panel (e.g. 'Google's backup and sync' or 'Divvy'). How can I ask permissions for that?

2 Answers

In Info.plist add the key NSAppleEventsUsageDescription in Source Code view

<key>NSAppleEventsUsageDescription</key>
<string>$(PRODUCT_NAME) needs to control System Events</string>

or Privacy - AppleEvents Sending Usage Description in the popup menu in Property List view.

The <string> value is an arbitrary description.

Moreover in Xcode 11 where Hardened Runtime is enabled you have to check the Apple Events checkbox

I found a reliable way to ask Automation permission in my app.

Run a command to send System Event in shell use osascript, like this:

osascript -e 'tell application "System Events" to keystroke "a"'

If this is the first time you have sent System Event on user's computer, an authorization dialog will pop up by system.

If you want to check the Automation permission status, you can run the same script via NSAppleScript.

NSAppleScript *aScript = [[NSAppleScript alloc] initWithSource:source];
NSDictionary<NSString *, id> *errorInfo;
[aScript executeAndReturnError:&errorInfo];

This code will silently fail in both cases when the first time sending System Event and when the authorization had denied. And the error code here will be -1743.

It should be noted that if the Accessibility permission is unauthorized, the error code here will be 1002. So first make sure that accessibility permissions are authorized.

Related