2016-12-04 2 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." 
    } 
} 

그리고 마지막으로 내 애플 스크립트가 여기에 있습니다 : 여기

나의하여 .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