停止呈现 PushNotification

Stop presenting PushNotification

当我在通知的 userInfo 中没有收到 userId 时,我不想显示通知。

那么如何停止显示通知?

我试过的代码:

  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("willPresent notification")

        let aps = notification.request.content.userInfo[AnyHashable("aps")]!
        guard let data = aps as? [String: Any] else{ return}

        if let userId = data["userId"] as? String {
            completionHandler([.alert, .badge, .sound])
        }else{
            return
        }
    }

但仍然显示通知。

这样试试

if let userId = data["userId"] as? String {
        completionHandler([.alert, .badge, .sound])
} else {
       completionHandler([])
}