6

I am new to OSX development and I am making an app which fires a notification when something happens. But it isn't showing the notification when the app is the key app, as it is the default behavior. I want to show them even when the app IS the key app. However I only found solutions to this matter that were written in objective-c but right now I am working with Swift. I was wondering how I could I implement it with Swift.

sbooth
  • 16,646
  • 2
  • 55
  • 81
Tommuu
  • 81
  • 1
  • 11

1 Answers1

15

To ensure the notifications are always shown you'll need to set a delegate for NSUserNotificationCenter and implement userNotificationCenter(center:shouldPresentNotification:) -> Bool. The documentation says this message is

Sent to the delegate when the user notification center has decided not to present your notification.

You can implement the delegate in any class of your choosing. Here is an example:

class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self
    }

    func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
        return true
    }
sbooth
  • 16,646
  • 2
  • 55
  • 81
  • This did the trick! Thanks! So the arrow is like a return type? Like I said, I am new to OSX and Swift development, I am trying to learn. – Tommuu Feb 24 '15 at 22:35
  • Yes, `->` indicates the return type of a function. – sbooth Feb 24 '15 at 22:36
  • Ah, I see. I am more used to C# and PHP so it is challenging learn swift. Thanks for your help. – Tommuu Feb 24 '15 at 22:42
  • 1
    I got it working by using an extension: (swift 3) https://gist.github.com/eonist/903e46b811c5eeeef84da2015c567b1b – Sentry.co Aug 13 '17 at 22:45