应用程序位于最前端时显示NSUserNotification的横幅

时间:2015-08-07 03:02:51

标签: macos swift delegates nsusernotificationcenter

我想在应用最前面时显示用户通知。 我找到了下面的代码,但我不确定如何使用委托:它似乎只返回一个布尔值。

class MyNotificationDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {

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

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

我尝试了一些句子:

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

delegate.userNotificationCenter(notificationcenter, shouldPresentNotification: notification)

但它不会显示横幅。 我知道对于NSUserNotificationCenterdeliverNotification:方法是展示横幅的方式。但我不确定NSUserNotificationCenterDelegate协议。

如何始终显示通知横幅?

1 个答案:

答案 0 :(得分:2)

您的通知中心委托和委托方法应该在AppDelegate中实现然后它可以工作。如果你在任何其他类中实现,它将不会作为横幅呈现,尽管它默默地出现在通知面板中。

我尝试如下并且正在工作:

@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)
    }
}