xcode - 如何在 swift 2 命令行工具中创建最小守护进程?

标签 xcode macos swift cocoa swift2

我想做什么

我想在 命令行工具 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/

相关文章:

macos - 使用Python 3在scikit-learn上进行大数据序列化

swift - 如何在静态 UITableviewCell 中使用 setTitleForState 更改 UIButton 标题

iphone - dyld : Library not loaded:/System/Library/Frameworks/Accounts. 框架/账户

macos - QML 中的视网膜支持

c++ - libc++abi.dylib : terminate called throwing an exception Abort trap: 6

ios - LazyVStack 在更改 SwiftUI 时初始化所有 View

ios - CloudKit更新通知可以将应用程序从 "Not running"状态唤醒吗?

c++ - 如何在 Xcode 中创建一个新的 C++ 项目?

iOS : Xcode Crash when configure SVN

c++ - main() 中的函数在前一个函数完成之前执行(c++ Xcode)