Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Created January 11, 2016 11:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save odrobnik/e8ac59e13b62ea80b623 to your computer and use it in GitHub Desktop.
Save odrobnik/e8ac59e13b62ea80b623 to your computer and use it in GitHub Desktop.
Calling AppleScript from Swift App, passing a parameter
// Swift version of https://developer.apple.com/library/mac/technotes/tn2084/_index.html
@IBAction func testButtonPushed(sender: AnyObject) {
let URL = NSBundle.mainBundle().URLForResource("SendFinderMessage", withExtension: "scpt")!
var errors: NSDictionary?
let script = NSAppleScript(contentsOfURL: URL, error: &errors)!
let message = NSAppleEventDescriptor(string: "Message from App")
let parameters = NSAppleEventDescriptor.listDescriptor()
parameters.insertDescriptor(message, atIndex: 1)
var psn = ProcessSerialNumber(highLongOfPSN: UInt32(0), lowLongOfPSN: UInt32(kCurrentProcess))
let target = NSAppleEventDescriptor(descriptorType: DescType(typeProcessSerialNumber), bytes:&psn, length:sizeof(ProcessSerialNumber))
let handler = NSAppleEventDescriptor(string: "show_message")
let event = NSAppleEventDescriptor.appleEventWithEventClass(AEEventClass(kASAppleScriptSuite), eventID: AEEventID(kASSubroutineEvent), targetDescriptor: target, returnID: AEReturnID(kAutoGenerateReturnID), transactionID: AETransactionID(kAnyTransactionID))
event.setParamDescriptor(handler, forKeyword: AEKeyword(keyASSubroutineName))
event.setParamDescriptor(parameters, forKeyword: AEKeyword(keyDirectObject))
// ObjC version compares this to nil, but it is non optional!
let descriptor = script.executeAppleEvent(event, error: &errors)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment