You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift macOS菜单栏应用 点击菜单项触发AppleScript实现方案

macOS菜单栏菜单项触发AppleScript实现方案

不需要改动原有功能逻辑,只需要补充3部分内容即可实现需求:

1. 新增AppleScript执行方法

在AppDelegate类内部,和其他@objc点击回调方法平级的位置,添加如下私有方法,内置你准备好的AppleScript逻辑:

private func runCustomAppleScript() {
    // 嵌入准备好的AppleScript脚本内容
    let scriptContent = """
if running of application "System Preferences" then
    try
        tell application "System Preferences" to quit
    on error
        do shell script "killall 'System Preferences'"
    end try
    delay 0.1
end if

repeat while running of application "System Preferences" is true
    delay 0.1
end repeat

tell application "System Preferences" to ¬
    set the current pane to pane id ¬
        "com.apple.preferences.sharing"

tell application "System Events"
    tell front window of application process "System Preferences"
        repeat until (exists checkbox 1 of row 5 of table 1 of scroll area 1 of group 1)
            delay 0.01
        end repeat
        click checkbox 1 of row 5 of table 1 of scroll area 1 of group 1
        delay 0.1
    end tell
end tell

tell application "System Preferences" to quit
"""
    var executionError: NSDictionary?
    guard let script = NSAppleScript(source: scriptContent) else { return }
    // 执行脚本
    script.executeAndReturnError(&executionError)
    // 可选:打印执行错误方便调试
    if let err = executionError {
        print("脚本执行失败:", err)
    }
}

2. 修改「One」菜单项的点击回调

找到原代码里的didTapOne()方法,在原有切换状态栏图标的逻辑下,新增一行调用上面写好的脚本执行方法即可,原有功能完全保留:

@objc func didTapOne() {
    changeStatusBarButton(number: 1)
    // 新增脚本调用逻辑
    runCustomAppleScript()
}

其余didTapTwo、didTapThree、退出菜单项的代码完全不需要改动,原有交互不受任何影响。

3. 必要配置(否则脚本无法正常运行)

因为脚本需要控制系统偏好设置、模拟UI点击,必须完成两个配置:

  • 关闭应用沙盒:在Xcode左侧项目导航栏选中项目,选择对应Target,打开Signing & Capabilities标签页,找到App Sandbox项点击左侧叉号移除,沙盒环境下应用无权向其他程序发送Apple事件
  • 开启辅助功能权限:第一次运行App点击「One」菜单项时,系统会弹出权限申请,按提示跳转到系统设置的隐私与安全性-辅助功能页面,给你的App勾选权限;如果没有弹出提示,手动进入上述路径勾选即可,配置完成后重启App生效。

调试提示:如果脚本运行没有达到预期,可以看Xcode控制台打印的错误信息,90%以上的运行异常都是权限配置不正确导致的。


内容的提问来源于stack exchange,提问作者Zezinas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 15:36:21