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

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

资源:

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])
    }

关于swift - 为什么我用UNUserNotificationCenter创建的本地通知没有显示在屏幕的右上角?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60050210/

10-16 13:31