Silve2611 Silve2611 - 15 days ago 7
Swift Question

Get return values from Applescript in Swift

Is it possible to run a Applescript in Swift and receive the return values?
I have a script like the following. How can I run this in swift and receive the return value?

global frontApp
set windowTitle to "
tell application "System Events"
set frontApp to first application process whose frontmost is true
end tell
return {frontApp}


my code would be as follows

var set: String = "set windowTile to \"\"\n"
var tell: String = "tell application \"System Events\"\n"
var setFrontApp: String = "set frontApp to first application
process whose frontmost is true\n"
var setFrontAppName: String = "set frontAppName to name of frontApp\n"
var tellProcces: String = "tell process frontAppName\n"
var tellFirst: String = "tell (1st window whose value of attribute
\"AXMain\" is true)\n"
var setWindowTitle: String = "set windowTitle to value of
attribute \"AXTitle\"\n"
var endTellFirst: String = "end tell\n"
var endTellProcess: String = "end tell\n"
var endTell: String = "end tell"
var startAtLoginScript: NSAppleScript = NSAppleScript(source: tell
+ deleteItem + endTell)!
startAtLoginScript.executeAndReturnError(errorInfo)


Can you tell me where my result should be or what I did wrong? If I print out errorInfo or tracking the result is some strange number.

foo foo
Answer

NSAppleScript is a mostly useless hunk of junk. If you want to integrate your own AppleScript code into your ObjC/Swift project, use the AppleScript-ObjC bridge, which uses standard ObjC messaging and provides automatic bridging between most AS types and their Foundation equivalents:

http://appscript.sourceforge.net/asoc.html

http://macscripter.net/viewtopic.php?pid=175562#p175562

If you want to execute user-supplied scripts, you generally want to use NSUserAppleScriptTask. Functionally it's even lamer than NSAppleScript (no persistence support); however, it is sandbox-friendly whereas NSAppleScript (which runs in-process) is not.

https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSUserAppleScriptTask_Class/