title: How to create a minimal daemon process in a swift 2 command line tool?
body: <h1>What I am trying to do</h1>
  
  <p>I want to run a daemon process that can listen to OSX system events like <code>NSWorkspaceWillLaunchApplicationNotification</code> in an <code>command line tool</code> xcode project? Is that possible? And if not, why not and are there any work arounds or hacks?</p>
  
  <h1>Some code samples</h1>
  
  <p>The following sample code from a <code>swift 2</code> <code>cocoa application</code> project sets up a system event listener, which calls <code>WillLaunchApp</code> every time an OSX app gets started. (<em>this works just fine</em>)</p>
  
  <pre><code>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)
      }
  }
  </code></pre>
  
  <p>In contrast this simingly similar <code>swift 2</code> <code>command line tool</code> project <strong>will not call</strong> <code>WillLaunchApp</code>. </p>
  
  <pre><code>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)
  }
  </code></pre>
  
  <p>I am guessing I am missing some <code>cocoa</code> and/or <code>xcode</code> fundamentals here, but I cannot figure out which ones. Maybe it is related to the while-true loop, which might be blocking the events. If so, is there a <strong>correct</strong> way to run a <strong>daemon</strong> process?</p>