gpt4 book ai didi

swift - 从菜单栏项运行 shell 命令

转载 作者:搜寻专家 更新时间:2023-11-01 05:33:14 24 4
gpt4 key购买 nike

我关注了一个非常有帮助的 guide创建一个简单的菜单栏应用程序,它有两个操作。但是,我希望在选择这些操作之一时执行 2 个 shell 命令。

Xcode 中的当前函数是:

func constructMenu() {
let menu = NSMenu()

menu.addItem(NSMenuItem(title: "ON", action: #selector(AppDelegate.printQuote(_:)), keyEquivalent: "S"))
menu.addItem(NSMenuItem(title: "OFF", action: #selector(AppDelegate.printQuote(_:)), keyEquivalent: "R"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit SMAC", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))

statusItem.menu = menu

当我点击菜单栏时,这会显示三个选项:

Screenshot of the menu bar options

然而,这就是我的 Cocoa 知识不足的地方。我希望在单击 ON 操作时执行以下 shell 脚本:

chmod u+x ~/Desktop/Mask.sh
~/Desktop/Mask.sh

最后在按下 OFF 按钮时执行以下两个 bash 脚本:

chmod u+x ~/Desktop/Unmask.sh
~/Desktop/Unmask.sh

最佳答案

以下两个类应该是相关的:ProcessNSUserUnixTask .

Process
An object representing a subprocess of the current process.
Using the Process class, your program can run another program as a subprocess and can monitor that program’s execution. A Process object creates a separate executable entity; it differs from Thread in that it does not share memory space with the process that creates it.

例如,这将是您用来chmod 脚本的内容。

Foundation | Streams, Sockets, and Ports | Process

NSUserUnixTask
An object that executes unix applications.
The NSUserUnixTask class is intended to run unix applications, typically a shell script, from your application. It is intended to execute user-supplied scripts, and will execute them outside of the application's sandbox, if any.

这是可用于执行您的 shell 脚本的内容。

Foundation | Processes and Threads | NSUserUnixTask

关于swift - 从菜单栏项运行 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49682489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com