我正在寻找一种从命令行工具发送命令(带参数)到正在运行的Cocoa应用程序的方法。这个是可能的吗?
如果我的Cocoa应用程序打开并运行,我希望它能从终端接收基本事件。如何在CLI-target和Cocoa-target之间通信?
我发现的唯一方法是使用AppleScript并为应用程序添加脚本化。这是唯一的出路吗?
发布于 2017-03-19 02:45:53
要从终端向应用程序发送命令,您可以使用URL方案。
在info.plist中注册一个方案(本例中“yourScheme”是方案标识符),然后监听事件:
NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(handleGetURLEvent(event:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
获取事件的内容。
@objc func handleGetURLEvent(event: NSAppleEventDescriptor!, withReplyEvent: NSAppleEventDescriptor!) {
if let text = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)) {
// you may want to filter the commands here
if text.contains("yourScheme://doStuff") {
} else if ...
}
}
来自终端的示例:
$ open "yourScheme://doStuff"
$ open "yourScheme://doSomethingElse"
https://stackoverflow.com/questions/42853260
复制相似问题