I'm working on a feature to enable user-provided scripts that will be executed by a Mac app.
NSUserScriptTask
underlies the script-calling code, and the NSUserAppleScriptTask
and NSUserAutomatorTask
subclasses both allow the setting of variables to pass information from Swift to the script:
Passing variables to an AppleScript
Setting NSUserAutomatorTask variables without requiring Automator Workflows to declare that variable
That leaves NSUserUnixTask
, which does not support setting variables. It instead supports a [String]
array called arguments
.
When executing the scripts, I will want to pass 3 variables from the Mac app:
let folderURL: String? = "/files/"
let fileURLs: [String] = ["/files/file1", "/files/file2"]
let selectionType: Int? = 1
let arguments: [String] = ["how", "should", "arguments", "be", "formatted", "?"]
let unixScript = try! NSUserUnixTask(url: url)
unixScript.execute(withArguments: arguments) { (error) in
if let error = error {
print(error)
}
}
The 3 swift variables must be condensed into a single [String]
array for NSUserUnixTask
to use as its arguments
parameter.
When the script runs, I want to then provide the script author access to the same arguments in a prototypical way:
#! /bin/bash
say "How should the script then access/parse the arguments?"
say $@ #says the arguments
Based on ease of use for the script author, how should the Swift code format its information into the arguments [String]
?
What boilerplate code could be provided to allow easy and pragmatic access to the parameters from the script?