Display banner for NSUserNotification while app is frontmost

899 Views Asked by At

I want to display user notifications while the app is frontmost. I found the code below, but I'm not sure how to use the delegate: it seems to just return a boolean value.

class MyNotificationDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {

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

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

I have tried some sentences like:

var delegate : MyNotificationDelegate = MyNotificationDelegate()
var notification:NSUserNotification = NSUserNotification()
var notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()

delegate.userNotificationCenter(notificationcenter, shouldPresentNotification: notification)

But it won't show the banner. I know that for NSUserNotificationCenter, the deliverNotification: method is the way to show the banner. But I'm not sure about the NSUserNotificationCenterDelegate protocol.

How can I always show the notification banner?

1

There are 1 best solutions below

0
On BEST ANSWER

Your notification centre delegate and delegate method should be implemented in AppDelegate then it works. If you implement in any other class, it won't present as banner though it silently comes in notification panel.

I tried as below and its working:

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {



    func applicationDidFinishLaunching(aNotification: NSNotification) {
        let notification: MyNotificationDelegate = MyNotificationDelegate()
        NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self;
        notification.setNotification("Hi", message: "How are you?")
    }

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

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }


}

class MyNotificationDelegate: NSObject {

    func setNotification(title: String, message: String)
    {
        let notification: NSUserNotification = NSUserNotification()
        notification.title = title
        notification.informativeText = message
        NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
    }
}