1

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

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

有没有办法在应用程序处于视图中时显示通知?

4

1 回答 1

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
    }
}
于 2015-11-04T19:09:13.833 回答