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

Display NSUserNotification when app is active

我目前正在制作一个使用以下代码显示通知的 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")

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

有没有办法在查看应用程序时显示通知?

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

extension AppController: NSUserNotificationCenterDelegate {

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

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