【问题标题】:What's the Difference Between NSUserNotification and UNUserNotification in macOS?macOS 中的 NSUserNotification 和 UNUserNotification 有什么区别?
【发布时间】:2021-01-24 02:30:23
【问题描述】:

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

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 都不会让系统在应用程序位于前面时显示通知。我想知道为什么?

谢谢。

【问题讨论】:

  • 如果您阅读docs,则不推荐使用NSUserNotification。您链接的 NSUserNotification 帖子是 5 年前的。
  • @Sweeper 谢谢。不过,它仍然有效。
  • 是的,为了向后兼容。
  • @Sweeper 好的。非常感谢。我应该关闭这个话题吗?

标签: swift macos nsusernotification unusernotification


【解决方案1】:

NSUserNotification 现已弃用。

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

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

改用 UNUserNotifaction

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 2011-01-21
    • 2015-04-07
    • 2010-10-02
    • 2011-12-12
    • 2010-09-16
    • 2012-03-14
    • 2012-02-06
    相关资源
    最近更新 更多