Skip to content

Instantly share code, notes, and snippets.

@chbeer
Forked from odrobnik/gist:e8ac59e13b62ea80b623
Last active September 13, 2023 01:02
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chbeer/3666e4b7b2e71eb47b15eaae63d4192f to your computer and use it in GitHub Desktop.
Save chbeer/3666e4b7b2e71eb47b15eaae63d4192f to your computer and use it in GitHub Desktop.
Calling AppleScript from Swift App, passing a parameter. Swift 3 version.
// updated for Swift 3
import Carbon
// Swift version of https://developer.apple.com/library/mac/technotes/tn2084/_index.html
@IBAction func testButtonPushed(sender: AnyObject) {
guard let url = NSBundle.main.url(forResource: "SendFinderMessage", withExtension: "scpt") else {
return
}
var errors: NSDictionary?
guard let script = NSAppleScript(contentsOf: url, error: &errors) else {
return
}
let message = NSAppleEventDescriptor(string: "Message from App")
let parameters = NSAppleEventDescriptor.init(listDescriptor: ())
parameters.insert(message, at: 1)
var psn = ProcessSerialNumber(highLongOfPSN: UInt32(0), lowLongOfPSN: UInt32(kCurrentProcess))
let target = NSAppleEventDescriptor(descriptorType: typeProcessSerialNumber, bytes:&psn, length:MemoryLayout<ProcessSerialNumber>.size)
let handler = NSAppleEventDescriptor(string: "show_message")
let event = NSAppleEventDescriptor.appleEventWithEventClass(AEEventClass(kASAppleScriptSuite), eventID: AEEventID(kASSubroutineEvent), targetDescriptor: target, returnID: AEReturnID(kAutoGenerateReturnID), transactionID: AETransactionID(kAnyTransactionID))
event.setParam(handler, forKeyword: AEKeyword(keyASSubroutineName))
event.setParam(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