1

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

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协议。

如何始终显示通知横幅?

4

1 回答 1

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)
    }
}
于 2015-10-21T06:05:30.287 回答