Swift NSUserNotification doesn't show while app is active

我是研究僧i 提交于 2019-12-23 20:42:00

问题


I am new to OSX development and I am making an app which fires a notification when something happens. But it isn't showing the notification when the app is the key app, as it is the default behavior. I want to show them even when the app IS the key app. However I only found solutions to this matter that were written in objective-c but right now I am working with Swift. I was wondering how I could I implement it with Swift.


回答1:


To ensure the notifications are always shown you'll need to set a delegate for NSUserNotificationCenter and implement userNotificationCenter(center:shouldPresentNotification:) -> Bool. The documentation says this message is

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

You can implement the delegate in any class of your choosing. Here is an example:

class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {

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

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


来源:https://stackoverflow.com/questions/28706937/swift-nsusernotification-doesnt-show-while-app-is-active

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!