【问题标题】:Why is the local notification I created with UNUserNotificationCenter not shown in the upper-right corner of my screen?为什么我使用 UNUserNotificationCenter 创建的本地通知未显示在屏幕右上角?
【发布时间】:2020-02-04 03:35:43
【问题描述】:

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

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

来源:

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

【问题讨论】:

    标签: swift macos cocoa


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      想看魔术吗?

      如果您使用多个显示器,请拔下它们,然后 tadaa - 通知工作。

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

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

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

      这太愚蠢了,几乎是可笑的。

      【讨论】:

        【解决方案3】:

        当应用在前台运行时,通知不会显示。 Relevant documentation.

        【讨论】:

          猜你喜欢
          • 2022-08-05
          • 1970-01-01
          • 1970-01-01
          • 2022-01-24
          • 1970-01-01
          • 2020-02-22
          • 2020-08-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多