点击通知时未调用 userNotificationCenter didReceive

userNotificationCenter didReceive is not being called when tapping a notification

我设置了以下本地通知:

    let content = UNMutableNotificationContent()
    content.title = "Some Title"
    content.body = "Some text"
    content.sound = UNNotificationSound.default

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 20, repeats: false) 

    let request = UNNotificationRequest(identifier: "OneDay", content: content, trigger: trigger)

    notificationCenter.add(request)

并且我已将以下内容添加到 AppDelegate

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

print("Notification Tapped")

if response.notification.request.identifier == "OneDay" {
    print("OneDay Notification Tapped")
}

completionHandler()
}

notificationCenter 已设置为:

let notificationCenter = UNUserNotificationCenter.current()

但是,none 以上打印语句有效。显示通知,我点击它,应用程序被带到前台,但没有任何内容打印到控制台。

我在这里遗漏了什么吗?我已经在模拟器和设备中进行了测试。结果相同。

我正在使用 XCode 11.5,为 12.0 进行部署。

我不确定发生了什么,因为我必须看到完整的代码,所以我只做了一个最小的例子让你理解。它在模拟器中也能完美运行。

如果您有任何问题,请随时告诉我!

首先确保您在设置委托或安排任何本地通知之前请求用户许可,否则您的通知将静默失败。

UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) { (isAuthorized, error) in
    // ...
}

完成请求授权后(状态为 已授权),只需设置您的委托:

UNUserNotificationCenter.current().delegate = self

创建您的通知:

let content = UNMutableNotificationContent()
content.title = "Title"
content.subtitle = "Subtitle"
content.body = "Body"
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "OneDay", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
    guard error == nil else {
        return
    }
    // ...
}

您的委托方法将按预期调用:

extension AppDelegate: UNUserNotificationCenterDelegate {

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


    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if response.notification.request.identifier == "OneDay" {
            // ...
        }
        completionHandler()
    }
}