1

I am currently making a XIB Menu Bar application that displays a notification using this code:

func showNotification(message:String, title:String = "App Name") -> Void {
    let notification = NSUserNotification()
    notification.title = title
    notification.informativeText = message
    NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
}

And calling it like this:

showNotification("\(song)\n\(artist)",title: "Now Playing")

The notification works when the Menu Bar application is hidden away (not shown), however when the user has it shown, the notification does not show.

Is there a way to show the notification while the application is in view?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
iProgram
  • 6,057
  • 9
  • 39
  • 80
  • FWIW: your code is not wrong, I've just tested in a Playground and it worked. – Eric Aya Nov 03 '15 at 18:18
  • @EricD. Then why is it working in the Playground (worked for me too), but not the application itself? The applescript version works fine, this means the logic does too right? – iProgram Nov 03 '15 at 18:25
  • Add a print statement - or better, make a breakpoint - in this function to check if it is actually called in your app. I'd say the bug is not with the code in your question but elsewhere in your app. – Eric Aya Nov 03 '15 at 18:27
  • @EricD. Logic works, the NSLog is displaying "test" like it should do – iProgram Nov 03 '15 at 18:29
  • @EricD. New problem, look at edit – iProgram Nov 03 '15 at 18:33
  • From the [docs](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSUserNotificationCenter_Class/index.html#//apple_ref/occ/cl/NSUserNotificationCenter): `The user notification center reserves the right to decide if a delivered user notification is presented to the user. For example, it may suppress the notification if the application is already frontmost (the delegate can override this action).` – Eric Aya Nov 03 '15 at 18:47
  • @EricD. Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/94125/discussion-between-iprogram-and-eric-d). – iProgram Nov 03 '15 at 18:53

1 Answers1

2

By default when your application is active, notifications delivered by your app are not shown. To get the expected behaviour, you have to use the user notification center delegate like below :

extension AppController: NSUserNotificationCenterDelegate {

    private func setupUserNotificationCenter() {
        let nc = NSUserNotificationCenter.defaultUserNotificationCenter()
        nc.delegate = self
    }

    public func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
        return true
    }
}
Jeremy Vizzini
  • 261
  • 1
  • 9