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

Swift NSUserNotification doesn't show while app is active

我是 OSX 开发的新手,我正在制作一个应用程序,它会在发生某些事情时触发通知。但是当应用程序是关键应用程序时它不会显示通知,因为这是默认行为。即使应用程序是关键应用程序,我也想向他们展示。 然而,我只找到了写在 objective-c 中的解决方案,但现在我正在使用 Swift。我想知道如何使用 Swift.

来实现它

为确保始终显示通知,您需要为 NSUserNotificationCenter 设置委托并实施 userNotificationCenter(center:shouldPresentNotification:) -> Booldocumentation 表示此消息是

Sent to the delegate when the user notification center has decided not to present your notification.

您可以在您选择的任何 class 中实施委托。这是一个例子:

class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self
    }

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