swift - macOS 中 NSUserNotification 和 UNUserNotification 有什么区别?

标签 swift macos nsusernotification unusernotification

我有以下代码行,可以通过单击“测试”按钮来发布通知。

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
        return true
    }
}

import Cocoa
import CloudKit

class HomeViewController: BasicViewController, NSUserNotificationCenterDelegate {
    override func viewDidLoad() {
    }

    @IBAction func testClicked(_ sender: NSButton) {
        let notification = MyNotificationDelegate()
        NSUserNotificationCenter.default.delegate = self
        notification.setNotification(title: "Test", message: "Test me if you can!")       
    }
}

import Cocoa

class MyNotificationDelegate: NSObject {
    func setNotification(title: String, message: String) {
        let notification: NSUserNotification = NSUserNotification()
        notification.title = title
        notification.informativeText = message
        NSUserNotificationCenter.default.deliver(notification)
    }
}

这段代码来自这个topic 。它是NSUserNotification

我看到了this topic 。它是UNUserNotification。基本上,它的作用与上面的相同。那么 NSUserNotification 和 UNUserNotification 有什么区别呢?我看到的唯一区别是后者可以让您了解用户是否允许发布通知。

如果应用程序位于前面,NSUserNotificationUNUserNotification 都不允许系统显示通知。我想知道为什么?

谢谢。

最佳答案

NSUserNotification 现已弃用。

UNNotification 对象包含初始通知请求,其中包含通知的有效负载以及通知发送的日期。

不要直接创建通知对象。处理通知时,系统会将通知对象传递给您的 UNUserNotificationCenterDelegate 对象。 UNUserNotificationCenter 对象还维护先前发送的通知列表,您可以使用 getDeliveredNotifications(completionHandler:) 方法来检索这些对象。

改用 UNUserNotifaction

关于swift - macOS 中 NSUserNotification 和 UNUserNotification 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64272748/

相关文章:

ios - 如何在 ios swift 中以编程方式将 Storyboard View Controller 加载到标签栏 Controller 中?

swift - 不确定的进度指示器没有动画

ios - AppCode 没有目标产品

objective-c - Mac OS X NSUserNotificationCenter 通知获取取消事件/回调

ios - 如何在收到推送通知时更新角标(Badge)号码

objective-c - 具有自定义 soundName 的 NSUserNotification

json - 使用回调从数据库调用中获取 JSON 值

ruby - 要求安装失败的 RVM 错误,状态为 :1

macos - SDL2 窗口在调整大小时变黑

objective-c - Cocoa Xcode - 如何将变量传递给函数