2015-11-03 25 views
1

我目前正在使用此代码显示通知的XIB菜单栏应用程序:显示NSUserNotification当应用程序被激活

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") 

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

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

+0

FWIW:您的代码没有错,我刚刚在Playground中测试过,它工作正常。 – Moritz

+0

@EricD。那么为什么它在Playground中工作(也适用于我),但不是应用程序本身? applescript版本正常工作,这意味着逻辑确实太对了? – iProgram

+0

在此函数中添加打印语句 - 或更好的做出断点 - 以检查它是否在您的应用程序中实际调用。我会说这个bug不是在你的问题中的代码,而是在你的应用程序的其他地方。 – Moritz

回答

0

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

extension AppController: NSUserNotificationCenterDelegate { 

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

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