osx

NSRunLoop

simple daemon application

A daemon process executes a program in the background, usually without user interaction. The example below shows how to create a daemon and register a listener, which monitors all open applications. The main part is the function call NSRunLoop.mainRunLoop().run(), which starts the daemon.

class MyObserver: NSObject
{
    override init() {
        super.init()

        // app listeners
        NSWorkspace.sharedWorkspace().notificationCenter.addObserver(self, selector: "SwitchedApp:", name: NSWorkspaceDidActivateApplicationNotification, object: nil)
    }

    func SwitchedApp(notification: NSNotification!)
    {
        print(notification)
    }
}


let observer = MyObserver()

// simply to keep the command line tool alive - as a daemon process
NSRunLoop.mainRunLoop().run()

You can also use this code as a basis for a server process.


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow