Make Cocoa app scriptable

I’d like to add one simple script command to a Cocoa/Swift app. However all the example tutorials are 1) really old 2) far more complicated than what I have in mind.

This is what I have in mind:

--I'd like my app to respond to this command:
tell application "MyApp"
	performMyCocoaClassMethod
end tell

That’s it. I know I need to build a sdef file and enable scriptability in xcode, but since I skipped learning ObjC and went straight to Swift, the rest of the process is very confusing.

Any pointers would be greatly appreciated.

Okay I’ve got it. I was able to dig up an Apple document (https://developer.apple.com/library/mac/samplecode/SimpleScriptingVerbs/Listings/ReadMe_txt.html) and find an example in Swift (http://stackoverflow.com/questions/25605805/swift-nsscriptcommand-performdefaultimplementation). My example isn’t that useful since desktop notifications are easily implemented using ASOC, but it’s a clear way to illustrate an Applescript command with arguments.

The sdef file:

The Swift class instantiated by the Applescript command:

Finally, the Applescript command:

tell application "NotiphyCMD"
	notiphy with title "Hello" and subtitle "world!"
end tell

A few notes:

in the sdef file, [format]NotiphyCMD.NotiphyWithParams[/format] is peculiar in that in ObjC [format]NotiphyWithParams[/format] is all that’s needed to refer to the class, but in Swift the dot notation is needed to resolve the path from the application to the class.

[format]NotiphyWithParams[/format] is a subclass of [format]NSScriptCommand[/format]. This is what does all the work. To get our subclass to respond to a scripting command, we use [format]override func performDefaultImplementation()[/format] This allows us to add ‘notiphy’ as our custom command. Expected arguments are added in the sdef file using <parameter. They are accessible inside the override func as a dictionary called [format]evaluatedArguments[/format]