Apple Script fails when run from within a macOS Swift-based application

1.5k views Asked by At

SOLUTION: I needed to do two things to solve my problem:

1) Add the following to my app's entitlements file:

<key>com.apple.security.temporary-exception.apple-events</key>
<array>
  <string>com.apple.Mail</string>
</array>

2) Add the following to my app's plist:

<key>NSAppleEventsUsageDescription</key>
<string>Please allow "your message here"</string>

This works on Mojave 10.14 (18A389)


I have a basic Swift-based macOS app. I'd like to use Apple Script to determine the number of unread email messages in Mail.app. I created a small Apple Script and tested it in Script Debugger (it works fine).

When I run the same script from within my app though it fails stating that the Mail application isn't running (even though it is):

let unreadEmailsScript = """
                         tell application "Mail"
                           get unread count of inbox
                         end tell
                         """
 if let scriptObject = NSAppleScript(source: unreadEmailsScript) {
   var errorDict: NSDictionary? = nil
   scriptObject.executeAndReturnError(&errorDict)

   if let error = errorDict {
     print(error)
   }
 }

Output:

{
    NSAppleScriptErrorAppName = Mail;
    NSAppleScriptErrorBriefMessage = "Application isn't running.";
    NSAppleScriptErrorMessage = "Mail got an error: Application isn't running.";
    NSAppleScriptErrorNumber = "-600";
    NSAppleScriptErrorRange = "NSRange: {33, 12}";
}

I haven't executed Apple Script from within an app before. Is this error due to a permissions problem?

1

There are 1 answers

3
vadian On

Yes, it's a permission problem.

Your app is sandboxed and you have to specify appropriate entitlements. Add this in the entitlements file of your app:

<key>com.apple.security.temporary-exception.apple-events</key>
<array>
    <string>com.apple.Mail</string>
</array>