macOS中的NSUserNotificationCenter

macOS中的NSUserNotificationCenter

我正在尝试创建一个将弹出通知的应用程序。
我在我的应用程序中使用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;
    }


当用户按“是”,“否”或单击通知时,我正在尝试执行代码。
我尝试改用此功能:

    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/

10-14 10:09