从AppleScript中调用Swift方法
问题描述:
我正在尝试编写一个调用Swift应用程序以获取值的AppleScript。该方法接受一个字符串并需要返回另一个字符串。从AppleScript中调用Swift方法
这里是我的.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>
对应的银行代码是相当简单:
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都没有报告问题。我错过了什么东西,或者把我的代码放在错误的地方?
答
对于这类脚本,我会推荐一种命令优先(又名动词优先)的方法,而不是您尝试的对象优先方法。你sdef看起来像这样(与你的项目的名称替换“MyProject的”,即应用程序的斯威夫特模块名称):
<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
+0
这是一个完美的答案。谢谢你的帮助。安德鲁 – iphaaw
'name =”my command“'因为'my'是一个AppleScript关键字,所以我建议不要将它用作名称的一部分。这样做不好。 – matt