应用处于活动状态时显示NSUserNotification

时间:2015-11-03 18:16:22

标签: swift macos cocoa swift2 nsusernotificationcenter

我目前正在制作一个使用此代码显示通知的XIB菜单栏应用程序:

func showNotification(message:String, title:String = "App Name") -> Void {
    let notification = NSUserNotification()
    notification.title = title
    notification.informativeText = message
    NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
}

并且这样称呼它:

showNotification("\(song)\n\(artist)",title: "Now Playing")

当隐藏菜单栏应用程序(未显示)时,通知有效,但是当用户显示时,通知不会显示。

在应用程序处于可见状态时,有没有办法显示通知?

1 个答案:

答案 0 :(得分:2)

默认情况下,当您的应用程序处于活动状态时,您的应用程序发送的通知不会显示。要获得预期的行为,您必须使用用户通知中心委托,如下所示:

extension AppController: NSUserNotificationCenterDelegate {

    private func setupUserNotificationCenter() {
        let nc = NSUserNotificationCenter.defaultUserNotificationCenter()
        nc.delegate = self
    }

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