2016-12-04 39 views
1

Swiftアプリケーションを呼び出して値を取得するAppleScriptを記述しようとしています。このメソッドは文字列を受け取り、別の文字列を返す必要があります。AppleScriptからSwiftメソッドを呼び出す

<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はここにある:ここで

は私の.sdfファイルである

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

私は実行AppleScriptは私のコマンドを認識しますが、私がそれに関連付けようとしたSwiftコードは呼び出されません。 XcodeまたはAppleScriptは問題を報告しません。私は何かを逃したり、間違った場所に自分のコードを入れたことがありますか?

+0

' name = "my command" 'myはAppleScriptのキーワードなので、名前の一部として使用しないことをお勧めします。それは良いことではありません。 – matt

答えて

2

このようなスクリプティングでは、試みているオブジェクト優先アプローチではなく、コマンド・ファースト(別名動詞)アプローチをお勧めします。あなたの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 tip from Swift NSScriptCommand performDefaultImplementation

+0

これは完璧な答えでした。ご協力いただきありがとうございます。アンドリュー – iphaaw

関連する問題