3

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?

RobertJoseph
  • 7,968
  • 12
  • 68
  • 113

1 Answers1

2

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>
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thank you @vadian. While this is definitely a step in the right direction the entitlements addition isn't sufficient under the latest version of Mojave. https://www.felix-schwarz.org/blog/2018/06/apple-event-sandboxing-in-macos-mojave – RobertJoseph Sep 21 '18 at 13:40
  • 1
    Adding the NSAppleEventsUsageDescription key (allow with a description string) to my app's plist, causes macOS to prompt for permission the first time my app launches. After that, everything works correctly. – RobertJoseph Sep 21 '18 at 13:52
  • You didn’t mention in your original question that you’re talking about Mojave. – vadian Sep 21 '18 at 14:17