下面的代码行可以通过单击Test按钮来发布通知。
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都不允许系统显示通知。我想知道为什么?
谢谢。
发布于 2020-10-09 03:19:27
现在不推荐NSUserNotification了。
UNNotification对象包含初始通知请求(该请求包含通知的有效负载)以及传递通知的日期。
不要直接创建通知对象。在处理通知时,系统将通知对象传递给UNUserNotificationCenterDelegate对象。UNUserNotificationCenter对象还维护先前传递的通知列表,您可以使用getDeliveredNotifications(completionHandler:)方法检索这些对象。
使用UNUserNotifaction代替
https://stackoverflow.com/questions/64272748
复制相似问题