Heitkamp
Heitkamp

Reputation: 73

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"
}

Upvotes: 7

Views: 4312

Answers (2)

Ashley Mills
Ashley Mills

Reputation: 53082

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

Upvotes: 8

Eric Aya
Eric Aya

Reputation: 70094

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.

Upvotes: 2

Related Questions