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

cyvaqqii  于 12个月前  发布在  iOS
关注(0)|答案(1)|浏览(139)

我正在开发一个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);
    }
}

问题是,当应用程序处于前台时,通知不会按预期显示,但当它处于后台时,它可以正常工作。
有没有关于如何解决这个问题并让通知在前台正确显示的想法?

i1icjdpr

i1icjdpr1#

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

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

相关问题