【发布时间】: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 有什么区别呢?我看到的唯一区别是后者可以让您了解用户是否允许发布通知。
NSUserNotification 或 UNUserNotification 都不会让系统在应用程序位于前面时显示通知。我想知道为什么?
谢谢。
【问题讨论】:
-
如果您阅读docs,则不推荐使用
NSUserNotification。您链接的NSUserNotification帖子是 5 年前的。 -
@Sweeper 谢谢。不过,它仍然有效。
-
是的,为了向后兼容。
-
@Sweeper 好的。非常感谢。我应该关闭这个话题吗?
标签: swift macos nsusernotification unusernotification