1

Here is my swift script which runs without errors, however, does nothing. I would expect it to display a notification in the notification center.

#!/usr/bin/env swift

import Foundation

let notification = NSUserNotification()
notification.title = "Hello"

let notificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()

class MyNotificationDelegate: NSObject, NSUserNotificationCenterDelegate
{
    func userNotificationCenter(center: NSUserNotificationCenter,
        shouldPresentNotification notification: NSUserNotification) -> Bool {
            return true
    }
}

notificationCenter.delegate = MyNotificationDelegate()
notificationCenter.deliverNotification(notification)

Can someone explain why this code snippet runs as expected from a playground (displays a Notification) but does nothing, when executed as script from a terminal.

dastrobu
  • 1,600
  • 1
  • 18
  • 32
  • "when executed as script from a terminal" Because the script ends and everything is torn down before the notification has a chance to be delivered to anything. – matt Aug 17 '15 at 22:25
  • That won't "keep it alive" - it just pauses, interrupting the progress of everything (it blocks). Compare my answer here: http://stackoverflow.com/a/30825723/341994 – matt Aug 17 '15 at 22:27
  • Hmm, this would imply that adding `NSRunLoop.currentRunLoop().run() ` should help, doesn't it? Unfortunately this does not help as well. – dastrobu Aug 17 '15 at 22:59
  • are you calling deliver notification before setting the delegate? – Neil Horton Nov 27 '15 at 15:50
  • good point, it would make sense to call `deliverNotification` after setting the delegate. However, the script does still not display the notification (edited the example script) – dastrobu Nov 28 '15 at 08:33

0 Answers0