Home » Swift » Can you execute an Applescript script from a Swift Application

Can you execute an Applescript script from a Swift Application

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have a simple AppleScript that sends an email. How can I call it from within a Swift application?

(I wasn’t able to find the answer via Google.)

Answers:

Untested, but it looks like one can do something like (arbitrary script path added):

import Foundation

let task = NSTask()
task.launchPath = "/usr/bin/osascript"
task.arguments = ["~/Desktop/testscript.scpt"]

task.launch()

Questions:
Answers:

As Kamaros suggests, you can call NSApplescript directly without having to launch a separate process via NSTask (as CRGreen suggests.)

Swift Code

let myAppleScript = "..."
var error: NSDictionary?
if let scriptObject = NSAppleScript(source: myAppleScript) {
    if let output: NSAppleEventDescriptor = scriptObject.executeAndReturnError(
                                                                       &error) {
        print(output.stringValue)
    } else if (error != nil) {
        print("error: \(error)")
    }
}

Questions:
Answers:

You can try NSAppleScript, from Apple’s Technical Note TN2084
Using AppleScript Scripts in Cocoa Applications
https://developer.apple.com/library/mac/technotes/tn2084/_index.html

NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
            @"\
            set app_path to path to me\n\
            tell application \"System Events\"\n\
            if \"AddLoginItem\" is not in (name of every login item) then\n\
            make login item at end with properties {hidden:false, path:app_path}\n\
            end if\n\
            end tell"];

returnDescriptor = [scriptObject executeAndReturnError: &errorDict];

Questions:
Answers:

I struggled few hours, but nothing worked. Finally I managed to run AppleScript through shell:

let proc = Process()
proc.launchPath = "/usr/bin/env"
proc.arguments = ["/usr/bin/osascript", "scriptPath"]
proc.launch()

Dunno is this the best way to do it, but at least it works.