Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing notification banner on Mac with Swift

I tried to show up some notification banners on Mac OS with Swift. But i get them only in the notification center, not as banner.

Do you have an idea? Here my simple code:

func showNotification() -> Void {
    let notification = NSUserNotification()
    notification.title = "Title of notification"
    notification.subtitle = "Subtitle of notification"
    notification.soundName = NSUserNotificationDefaultSoundName
    NSUserNotificationCenter.default.deliver(notification) 
}

@IBAction func btnPressed(_ sender: NSButton) {
    showNotification()
    testLbl.stringValue = "Button was pressed"
}
like image 270
Heitkamp Avatar asked Aug 29 '18 14:08

Heitkamp


2 Answers

You won't get a banner if your app is in the foreground.

Try using…

notification.deliveryDate = Date(timeIntervalSinceNow: 5)
NSUserNotificationCenter.default.scheduleNotification(notification)

and then switch to another app

like image 118
Ashley Mills Avatar answered Sep 30 '22 14:09

Ashley Mills


If, at the time of sending the notification, the app sending the notification is focused, then the notification won't show as a banner. An app can only deliver a banner notification if it is not active in the foreground.

Your code works well when your app is not the main focus, I've just tested it.

So, because you send the notification on a button click, the app is focused when the notification is sent: the notification only goes to the Notification Center, it is not shown as a banner.

This is a rule made on purpose by Apple.

like image 22
Eric Aya Avatar answered Sep 30 '22 13:09

Eric Aya