swift - macOS 中的 NSUserNotificationCenter

标签 swift macos

我正在尝试创建一个会弹出通知的应用程序。 我在我的应用程序中使用 NSUserNotificationCenterDelegate,如下所示:

class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
    let NScenter = NSUserNotificationCenter.default        

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        self.NScenter.delegate = self
        let notification = NSUserNotification.init();
        self.NScenter.deliver(notification)
    }

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

当用户按"is"、“否”或单击通知时,我尝试执行代码。 我尝试改用这个函数:

    func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) -> Bool {
        print("ok");
        return true;
    }

但是当我使用它时,通知没有显示。

最佳答案

我找到了一种方法,当使用这两个功能时,当用户单击它时,我可以弹出通知。

class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
    let NScenter = NSUserNotificationCenter.default        

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        self.NScenter.delegate = self
        let notification = NSUserNotification.init();
        self.NScenter.deliver(notification)
    }

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


    func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) -> Bool {
        print("ok");
        return true;
    }
}

关于swift - macOS 中的 NSUserNotificationCenter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51610489/

相关文章:

swift - 工具栏正在删除我在NavigationView中的后退按钮

ios - SpriteKit 游戏暂停

ios - 取消事件的调用

swift - Swift 中的抽象方法?

macos - 通过 PIP 安装 NPM,但得到 "npm: command not found"

ios - 有没有办法在 google 日历和 ios 日历中使用 URL 字段

swift - Xcode 6 : iOS Swift. 如何获取游戏帧率(fps)?

ios - 我什么时候应该调用 [NSUserDefaults standardUserDefaults] registerDefaults :] to ensure that . xib 文件可以立即访问首选项?

xcode - SpriteKit unarchiveFromFile 不会从 Assets 目录和图集中加载纹理

macos - 如何使用 GLFW 轮询 libdispatch block 中的事件?