You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native集成FCM:iOS前台无通知后台正常问题求助

解决React Native FCM iOS前台无通知问题

我之前帮不少开发者踩过这个坑——iOS后台能收通知但前台没反应,本质是iOS系统不会自动在前台展示推送通知,必须我们在原生层手动处理触发逻辑。结合你提到已经加了部分AppDelegate代码,我帮你梳理下关键遗漏点:

1. 确认UNUserNotificationCenter代理配置完整

首先要确保在AppDelegate.m里正确设置通知中心代理,并且请求了通知权限。在didFinishLaunchingWithOptions方法里补充以下代码:

#import <UserNotifications/UserNotifications.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // 保留你已有的其他代码...

  // 设置UNUserNotificationCenter代理
  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  center.delegate = self;

  // 请求通知权限(弹窗、声音、角标)
  [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge)
                        completionHandler:^(BOOL granted, NSError * _Nullable error) {
                          if (granted) {
                            [[UIApplication sharedApplication] registerForRemoteNotifications];
                          }
                        }];

  return YES;
}

2. 实现前台通知展示的核心方法

iOS 10+必须实现UNUserNotificationCenterDelegate的willPresentNotification方法,这个方法直接决定前台收到通知时是否展示。把这段代码加到AppDelegate.m中:

// iOS 10+ 前台接收通知时触发
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  // 指定前台展示通知的方式:弹窗+声音+角标,可按需调整
  completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge);

  // 可选:在原生层打印通知内容,方便调试
  NSDictionary *userInfo = notification.request.content.userInfo;
  if ([userInfo[@"gcm.message_id"] length] > 0) {
    NSLog(@"FCM前台通知内容: %@", userInfo);
  }
}

3. JS层监听逻辑(可选但建议补充)

如果需要在React Native代码里处理前台通知的业务逻辑,别忘了监听onMessage事件:

import messaging from '@react-native-firebase/messaging';
import { useEffect } from 'react';

// 在组件挂载时监听前台通知
useEffect(() => {
  const unsubscribe = messaging().onMessage(async remoteMessage => {
    console.log('前台收到FCM通知:', remoteMessage);
    // 这里可以用自定义弹窗组件或业务逻辑处理
  });

  return unsubscribe;
}, []);

4. 额外检查点

  • 确保Xcode的Capabilities中,Push Notifications已开启,Background Modes里的Remote notifications选项已勾选;
  • 确认FCM推送的payload包含notification字段(纯data类型的推送需要完全手动处理展示);
  • 测试时用真实iOS设备,模拟器偶尔会出现推送不触发的问题。

按这个流程调整后,iOS前台应该就能正常弹出通知了。

内容的提问来源于stack exchange,提问作者Eddie Roosenmaallen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:19:33