我想做什么
我想在 命令行工具
xcode 项目中运行一个可以监听 OSX 系统事件的守护进程,例如 NSWorkspaceWillLaunchApplicationNotification
?那可能吗?如果没有,为什么不呢?是否有任何解决方法或黑客攻击?
一些代码示例
swift 2
cocoa application
项目中的以下示例代码设置了一个系统事件监听器,它会在每次 OSX 应用程序时调用 WillLaunchApp
开始。 (这很好用)
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSWorkspace.sharedWorkspace()
.notificationCenter.addObserver(self,
selector: "WillLaunchApp:",
name: NSWorkspaceWillLaunchApplicationNotification, object: nil)
}
func WillLaunchApp(notification: NSNotification!) {
print(notification)
}
}
相比之下,这个非常相似的 swift 2
命令行工具
项目不会调用 WillLaunchApp
。
import Cocoa
class MyObserver: NSObject
{
override init() {
super.init()
NSWorkspace.sharedWorkspace()
.notificationCenter.addObserver(self,
selector: "WillLaunchApp:",
name: NSWorkspaceWillLaunchApplicationNotification, object: nil)
}
func WillLaunchApp(notification: NSNotification!) {
// is never called
print(notification)
}
}
let observer = MyObserver()
while true {
// simply to keep the command line tool alive - as a daemon process
sleep(1)
}
我猜我在这里遗漏了一些 cocoa
和/或 xcode
基础知识,但我不知道是哪些。也许它与 while-true 循环有关,它可能会阻止事件。如果是这样,是否有正确方法来运行守护进程进程?
最佳答案
事实证明,使用 while true
循环会阻塞主线程。
只需将 while true
循环替换为 NSRunLoop.mainRunLoop().run()
即可获得守护进程。
我阅读了 swifter 的来源(一个基于 swift 的服务器),它也在做同样的事情。
关于xcode - 如何在 swift 2 命令行工具中创建最小守护进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31469532/