iOS 14+ UNUserNotificationCenter 未按预期显示前台通知

iOS 14+ UNUserNotificationCenter not presenting foreground notifications as expected

提问人:desertSniper87 提问时间:10/11/2023 更新时间:10/11/2023 访问量:29

问:

我正在开发一个 iOS 应用程序,并尝试在 iOS 14 及更高版本中使用 UNUserNotificationCenter 处理前台通知。但是,当应用位于前台时,通知不会按预期显示。

这是我的代码:

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    NSLog(@"Foreground notification - appdelegate: %@", notification);

    NSDictionary *userInfo = notification.request.content.userInfo;
    // Foreground
    NSLog(@"APP_PUSH from foreground %@", userInfo);

    
    if (@available(iOS 14.0, *)) {
      completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionBadge);
    } else {
      completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
    }
}

问题是当应用程序在前台时,通知没有按预期显示,但在后台时它可以工作。

关于如何解决此问题并使通知在前台正确显示的任何想法?

IOS的 Objective-C

评论


答:

1赞 HangarRash 10/11/2023 #1

您需要为 iOS 14+ 添加选项,以允许在应用程序处于前台时显示通知。UNNotificationPresentationOptionList

if (@available(iOS 14.0, *)) {
  completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionList | UNNotificationPresentationOptionBadge);
} else {
  completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}