Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables to an AppleScript

The code to run my AppleScript in Xcode is the following:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Script" ofType:@"scpt"];

NSAppleScript *script = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];

[script executeAndReturnError:nil];

Before executing it, I was wondering if it was possible to set some variables up for it to use. In other words, I want to pass variables from my app to an AppleScript.

like image 751
Andrew Avatar asked Jan 18 '23 18:01

Andrew


1 Answers

The best example I've found is this code from Quinn "The Eskimo!" on the Apple Developer Forums:

https://forums.developer.apple.com/thread/98830

AppleScript file:

on displayMessage(message)  
    tell application "Finder"  
        activate  
        display dialog message buttons {"OK"} default button "OK"  
    end tell  
end displayMessage 

Call the AppleScript method from Swift, passing parameters:

import Carbon

// ...

let parameters = NSAppleEventDescriptor.list()
parameters.insert(NSAppleEventDescriptor(string: "Hello Cruel World!"), at: 0)

let event = NSAppleEventDescriptor(
    eventClass: AEEventClass(kASAppleScriptSuite),
    eventID: AEEventID(kASSubroutineEvent),
    targetDescriptor: nil,
    returnID: AEReturnID(kAutoGenerateReturnID),
    transactionID: AETransactionID(kAnyTransactionID)
)
event.setDescriptor(NSAppleEventDescriptor(string: "displayMessage"), forKeyword: AEKeyword(keyASSubroutineName))
event.setDescriptor(parameters, forKeyword: AEKeyword(keyDirectObject))

let appleScript = try! NSUserAppleScriptTask(url: yourAppleScriptFileURL)
appleScript.execute(withAppleEvent: event) { (appleEvent, error) in
    if let error = error {
        print(error)
    }
}
like image 79
pkamb Avatar answered Jan 25 '23 16:01

pkamb