使用 AppleScript 和 Javascript JXA 使 SwiftUI 应用程序可编写脚本

问题描述 投票:0回答:1

请注意,我已经仔细阅读了如何在 Swift MacOS 应用程序中实现 AppleScript 支持——但这对我不起作用。我认为它已经过时了。


在阅读了各种文档、指南和示例之后,我一直在尝试让 AppleScript / Javascript 支持在 SwiftUI 应用程序中工作。 (首先在 Macos Big Sur 中。)

主要问题好像是所有的文档、例子等都过时了

我可以把这个问题作为关于 Swift 5 +

AppDelegate
而不是 SwiftUI 的问题,我会遇到同样的问题。

所以这就是我到目前为止所拥有的......

  • Info.plist -(SwiftUI 中不存在)添加:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>NSAppleScriptEnabled</key>
    <true/>
    <key>OSAScriptingDefinition</key>
    <string>Progression.sdef</string>
</dict>
</plist>
  • Progression.entitlements 允许编写脚本。 (沙箱也已关闭。)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.app-sandbox</key>
    <false/>
    <key>com.apple.security.files.user-selected.read-only</key>
    <true/>
    <key>com.apple.security.automation.apple-events</key>
    <true/>
</dict>
</plist>
  • 然后我创建了我希望的工作
    Progression.sdef
    脚本定义文件。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dictionary SYSTEM "file://localhost/System/Library/DTDs/sdef.dtd">
<dictionary title="Progression Terminology">
    <suite name="Progression Suite" code="PrgN" description="Progression scripting classes and commands.">
        <command name="progress" code="proGress">
            <cocoa class="Progression.ProgressCommand"/>
        </command>
    </suite>
</dictionary>
  • ProgressCommand
    在 SwiftUI 应用程序中。
import Foundation
@objc class ProgressCommand: NSScriptCommand {
    @objc override func performDefaultImplementation() -> Any? {
        print("Called")
        return nil
    }
}
  • 我可以加载应用程序,并在 ScriptEditor > 打开字典中检测 sdef...
  • 在 AppleScript 中,我可以在应用程序上调用 quit(尽管我还没有测试过如果我拉出所有脚本项是否有效。):
tell application "Progression"
  quit
end tell
  • 在 AppleScript 中,如果我调用
    progress
    它似乎可以识别该命令,尽管我不确定它是否超过了
    .sdef
    级别......因为它失败了:
tell application "Progression"
  progress
end tell
error "Progression got an error: Can’t continue progress." number -1708

在这一点上我被困了几天。

编辑:我找到了这个答案:

https://stackoverflow.com/a/37202803/311660 尽管将代码添加到 SwiftUI 应用程序不起作用。

谢天谢地,提供了一个项目和代码(使用旧的 NSAppDelegate 样式。)可以独立工作。

如果我无法获得纯 SwiftUI 的有效答案,我将使用

NSAppDelegate
重新实现该应用程序,最终我只需要一个指向 ApppleScript 的有效链接。

问题仍然存在,这在 SwiftUI 应用程序中可能吗?

swift applescript macos-big-sur appleevents sdef
1个回答
2
投票

所以 https://stackoverflow.com/a/37202803/311660 中的答案解决了这个问题,它与 SwiftUI 配合得很好。

我的代码中的问题是我的命令名称。

<command name="progress" code="progress">

progress
是保留字(用于
progress indicator
,在我的示例代码中将其更改为
foobar
,解决了问题。

© www.soinside.com 2019 - 2024. All rights reserved.