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?
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: