Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kcrawford/00994c6246472d73e6a8893cb84d3e9c to your computer and use it in GitHub Desktop.
Save kcrawford/00994c6246472d73e6a8893cb84d3e9c to your computer and use it in GitHub Desktop.
Calling AppleScript from Swift App, passing a parameter. Basic
import Carbon
//guard let url = Bundle.main.url(forResource: "SendFinderMessage", withExtension: "scpt") else {
// exit(0)
//}
//guard let script = NSAppleScript(contentsOf: url, error: &errors) else {
// exit(0)
//}
var errors: NSDictionary?
let script = NSAppleScript(source: "on show_message(message)\n tell app \"System Events\" to display dialog message\n return \"Cool\"\n end")
let handler = NSAppleEventDescriptor(string: "show_message")
let message = NSAppleEventDescriptor(string: "Message from App")
let parameters = NSAppleEventDescriptor.init(listDescriptor: ())
parameters.insert(message, at: 1)
let event = NSAppleEventDescriptor.appleEvent(withEventClass: AEEventClass(kASAppleScriptSuite), eventID: AEEventID(kASSubroutineEvent), targetDescriptor: nil, returnID: AEReturnID(kAutoGenerateReturnID), transactionID: AETransactionID(kAnyTransactionID))
event.setParam(handler, forKeyword: AEKeyword(keyASSubroutineName))
event.setParam(parameters, forKeyword: AEKeyword(keyDirectObject))
let returnedDescriptor = script?.executeAppleEvent(event, error: &errors)
returnedDescriptor?.stringValue
errors
@AlabasterAxe
Copy link

where does keyASSubroutineName come from? I'm getting an error about it being undefined in the scope

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment