swiftxcodeapplescriptscripting-bridge

Get permission to use ScriptingBridge


I try to use ScriptingBridge in Swift. This works pretty good, if I compile my app and run the app from the Terminal, but running it from Xcode or open it from Finder doesn't work. More in detail, this is my code:

@objc protocol MailMessage {
    @objc optional var id: Int { get }
    @objc optional var dateSent: Date { get }
    @objc optional var sender: String { get }
    @objc optional var source: String { get }
}
extension SBObject: MailMessage {}

@objc protocol MailApplication {
    @objc optional var selection: SBElementArray { get }
    @objc optional func extractNameFrom(_ x: String) -> String
    @objc optional func extractAddressFrom(_ x: String) -> String
}

extension SBApplication: MailApplication {}
if let mail: MailApplication = SBApplication(bundleIdentifier: "com.apple.mail") {

    if let selection = mail.selection as? [MailMessage] {
        // sort to get the newest message first
        let sorted = selection.sorted { $0.id! > $1.id! }
        let message = sorted[0]

        // print the name of the sender
        if let sender = message.sender {
            let name = mail.extractNameFrom!(sender)
            print(name)
        }
    }
}

From the terminal I successfully get printed the name of the sender. Starting from Xcode, mail.selection is nil.

But:

print(mail)

gives me:

<SBScriptableApplication @0x600000c91b00: application "Mail" (689)>

So I tested a little more and I added two things to my protocol:

@objc protocol MailApplication {
    @objc func activate()
    @objc var delegate: SBApplicationDelegate? { get set }
    ...

Now I did the following:

if let mail: MailApplication = SBApplication(bundleIdentifier: "com.apple.mail") {
    mail.delegate = self
    mail.activate()
    ...
func eventDidFail(_ event: UnsafePointer<AppleEvent>, withError error: Error) -> Any? {
    print(error)
}

First: mail.activate() opens up the Mail application.

But: accessing the SBObject doesn't work, as I get the following error:

Error Domain=NSOSStatusErrorDomain Code=-1743 "(null)" UserInfo={ErrorNumber=-1743}

I googled for the error 1743 and it means, that my application doesn't have the permission for Automation. So I tried to add it in Xcode in two ways:

Unfortunately none of them work. In macOS settings I cannot add any application to the Automation part.

Any ideas?


Solution

  • In macOS 10.14+ you have to add the key

    Privacy - AppleEvents Sending Usage Description
    

    aka NSAppleEventsUsageDescription in Info.plist. The string value is displayed to the user