为什么我使用 UNUser通知中心创建的本地通知没有显示在屏幕的右上角?



运行下面的代码不会在屏幕右上角显示通知(作为横幅或警报(。通知将显示在通知中心中。

我确保在我的系统上禁用了"请勿打扰"。我还尝试了"系统偏好设置"->"通知"->"我的应用程序名称"中的"横幅"和"警报"设置。

源:

import Cocoa
import UserNotifications
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
print("requestNotificationAuthorization: granted=(granted) error=(String(describing: error))")
}

let content = UNMutableNotificationContent()
content.title = "bar"
content.body = "foo"
content.categoryIdentifier = "alarm"
let uuidString = UUID().uuidString
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: { error in
print("completion handler called")
if error != nil {
print("notification center error: (String(describing: error))")
}
})
}
func applicationWillTerminate(_ aNotification: Notification) {
}
}

控制台输出:

requestNotificationAuthorization: granted=true error=nil
completion handler called

如果您想在应用程序处于前台时看到通知横幅,请使用以下方法

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Forground notifications.
completionHandler([.alert, .sound])
}

想看魔术吗?

如果您正在使用多个显示器,请拔下它们,然后 tadaa - 通知有效。

我确保在我的系统上禁用了"请勿打扰"。

转到 MacSystem Preferences->Notifications->Do not disturb (1st item on the list)

事实证明,默认情况下,如果您正在镜像显示器,则会启用"请勿打扰"模式,并且您不会收到任何通知。因此,取消选中它,重新插入其他显示器并继续编码。

这太愚蠢了,几乎很有趣。

当应用在前台运行时,不会显示通知。相关文档。

最新更新