UNUserNotification 不会在 iOS 12 下触发我的本地通知

UNUserNotification doesn't fire out my local notification under iOS 12

在代码中我尝试这样做:

import UserNotifications

if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound]) { _, _ in }
        let content = UNMutableNotificationContent()
        content.title = "Hello Staff"
        content.body = "Customer just ordered a milk with croissant"
        content.sound = UNNotificationSound.default()
        let date = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date(timeIntervalSinceNow: 10))
        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
        let request = UNNotificationRequest(identifier: "abcde", content: content, trigger: trigger)
        center.add(request)
}

一切都发生在 AppDelegate 之内。但是我看不到任何本地通知。为什么?

您的代码运行良好。我想问题是当您收到通知时您的应用程序处于活动状态。 iOS 仅在应用未激活时显示系统通知。如果通知触发时应用处于活动状态,系统会触发 UNUserNotificationCenterDelegate 方法,以便您可以自己处理通知。

因此,由于您设置了延迟 10 秒的通知时间,因此您需要 运行 您的应用,然后关闭它并等待 10 秒。如果您授予您的应用这样的权限,应该会出现通知。