How to create a minimal daemon process in swift 2 command line tool?

What am i trying to do

I want to start a daemon process that can listen to OSX system events, such as NSWorkspaceWillLaunchApplicationNotificationin an command line toolxcode project ? Is it possible? And if not, why not and are there any jobs or hacks?

Some code examples

The following sample code from the project swift 2 cocoa applicationinstalls a system event listener that WillLaunchAppfires every time the OSX application starts. (this works just fine)

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)
    }
}

In contrast, a similarly similar project swift 2 command line tool will not be called 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, . , daemon?

+4
2

, while true . while true NSRunLoop.mainRunLoop().run(), .

swifter ( ), .

+6

Swift 3 :

RunLoop.main.run()
+3

Source: https://habr.com/ru/post/1598328/


All Articles