1

我正在尝试编写一个调用我的 Swift 应用程序以获取值的 AppleScript。该方法接受一个字符串并且需要返回另一个字符串。

这是我的 .SDF 文件:

<suite name="My Suite" code="MySU" description="My AppleScript suite.">
    <class name="application" code="capp" description="An application's top level scripting object.">
        <cocoa class="NSApplication"/>
        <element type="my types" access="r">
            <cocoa key="types"/>
        </element>
    </class>

    <command name="my command" code="MyCOMMND" description="My Command">
        <parameter name="with" code="MyPR" description="my Parameter" type="text">   
            <cocoa key="myParameter"/>
        </parameter>
        <result type="text" description="the return value"/>

        <cocoa method="myCommand:"/>
    </command>
</suite>

对应的 Swift 代码相当简单:

func myCommand(_ command: NSScriptCommand) -> String
{
    if let myParameter = command.evaluatedArguments?["myParameter"] as? String
    {
        return "Hello World!"
    }
    else
    {
        return "Nothing happening here. Move on."
    }
}

最后我的 AppleScript 在这里:

tell application "MyApp"
    set r to my command with "Hello"
end tell

当我执行 AppleScript 时,它会识别我的命令,但它不会调用我尝试与之关联的 Swift 代码。Xcode 或 AppleScript 都没有报告问题。我是否遗漏了什么或将我的代码放在了错误的位置?

4

1 回答 1

2

对于这种脚本,我建议使用命令优先(也称为动词优先)方法,而不是您尝试的对象优先方法。您的 sdef 看起来像这样(将“MyProject”替换为您的项目名称,即您的应用程序的 Swift 模块名称):

<dictionary xmlns:xi="http://www.w3.org/2003/XInclude">
<suite name="My Suite" code="MySU" description="My AppleScript suite.">

    <command name="my command" code="MySUCMND" description="My Command">
        <cocoa class="MyProject.MyCommand"/>
        <parameter name="with" code="MyPR" description="my Parameter" type="text">   
            <cocoa key="myParameter"/>
        </parameter>
        <result type="text" description="the return value"/>
    </command>

</suite>
</dictionary>

该类MyCommand应如下所示:

class MyCommand : NSScriptCommand {

    override func performDefaultImplementation() -> Any? {
        if let _ = self.evaluatedArguments?["myParameter"] as? String
        {
            return "Hello World!"
        }
        else
        {
            return "Nothing happening here. Move on."
        }

    }
}

“ModuleName.ClassName” sdef 提示来自Swift NSScriptCommand performDefaultImplementation

于 2016-12-05T16:28:57.560 回答