设置NSUserAutomatorTask变量,而不需要Automator工作流来声明该变量

pka*_*amb 6 macos workflow cocoa applescript automator

我正在使用macOS 10.13中的Automator应用程序创建NSUserAutomatorTask一个.workflow文件.

我通过variables属性将变量传递给工作流:

https://developer.apple.com/documentation/foundation/nsuserautomatortask/1418099-variables

父应用程序是沙盒..applicationScriptsDirectory当未设置变量时,或者在应用程序中设置相同的变量并在工作流中声明时,脚本位于并成功运行.

if let workflow = try? NSUserAutomatorTask(url: url) {

    workflow.variables = ["randomVariable": "value"] // NOTE

    workflow.execute(withInput: nil) { (value, error) in
        if let error = error {
            print(error) // No variable named "randomVariable"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

工作流无法运行并显示错误:

没有名为"randomVariable"的变量

但是,如果我编辑工作流并添加一个变量以匹配代码中的一个,那么一切都很好.

将var添加到工作流程

我不再收到错误,工作流程正确执行:

执行工作流程

这是一个问题,因为我想将多条信息作为变量传递给任何潜在的工作流程,并且每个工作流程单独决定处理每个所需的参数.

我不想要求每个工作流声明我的应用程序可选择提供的变量.

请注意,在我的示例工作流程中,从不使用变量.我不希望声明它的额外要求.

有没有办法避免每个工作流声明我的应用程序在执行工作流时传递的变量?

或者,有没有办法检查工作流声明了哪些变量?然后我只能传递工作流实际使用的那些.

pka*_*amb 0

方法和AMWorkFlowsetValue(_:forVariableWithName:)valueForVariable(withName:)可以安全地确定该变量是否在工作流文件中设置。

\n

因此,在AMWorkFlow您的NSUserAutomatorTask. 仅设置脚本正在使用的变量,如以下所示AMWorkFlow

\n
if let automatorTask = try? NSUserAutomatorTask(url: url) {\n    if let varChecker = try? AMWorkflow(contentsOf: url) {\n        automatorTask.variables = POSSIBLE_VARIABLES.filter {\n            return varChecker.setValue($0.value, forVariableWithName: $0.key)\n            // -or- //\n            return varChecker.valueForVariable(withName: $0.key) != nil\n        }\n    }\n        \n    automatorTask.execute(withInput: nil, completionHandler: nil)\n}\n
Run Code Online (Sandbox Code Playgroud)\n

AMWorkFlow根本不在沙盒中执行,因此您必须使用它NSUserAutomatorTask来实际运行工作流程。

\n
do {\n    try AMWorkflow.run(at: url, withInput: nil)\n} catch let error {\n    print(error)\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

Automator 运行此工作流程时遇到错误:

\n

沙盒应用程序无法使用 Automator.framework 来运行工作流程。

\n

错误域=com.apple.Automator代码=0“Automator在运行此工作流程时遇到错误:\xe2\x80\x9c沙盒应用程序无法使用Automator.framework来运行工作流程。\xe2\x80\x9d”UserInfo={NSUnderlyingError=0x604000e498a0 {Error Domain=com.apple.Automator Code=0“沙盒应用程序无法使用 Automator.framework 来运行工作流程。” UserInfo={NSLocalizedDescription=沙盒应用程序无法使用 Automator.framework 运行工作流程。}}, NSLocalizedDescription=Automator 运行此工作流程时遇到错误:\xe2\x80\x9c沙盒应用程序无法使用 Automator.framework 运行工作流程。\xe2\ x80\x9d, NSLocalizedFailureReason=沙盒应用程序无法使用 Automator.framework 来运行工作流程。}

\n
\n