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

React Native iOS端messaging通知打开监听方法失效,Android正常

React Native iOS 中 Firebase Messaging onNotificationOpenedApp 和 getInitialNotification 失效问题排查方案

一、基础推送配置校验

  • 确认GoogleService-Info.plist已正确导入主App Target,且Bundle ID与Firebase控制台配置完全一致
  • 检查Info.plist是否添加后台推送权限:
    <key>UIBackgroundModes</key>
    <array>
      <string>remote-notification</string>
    </array>
    
  • 确保Xcode项目的Signing & Capabilities中已开启Push Notifications,并勾选Background Modes下的Remote notifications
  • 使用真机测试,iOS模拟器不支持远程推送功能

二、Podfile 配置优化

你当前的Podfile缺少Firebase Messaging的模块化头配置,且部分依赖的静态化处理不完整,建议调整如下:

  1. 补充Firebase Messaging的模块化头设置:
    pod 'FirebaseMessaging', :modular_headers => true
    
  2. 确保$RNFirebaseAsStaticFramework = true放在所有Firebase pod声明之前:
    $RNFirebaseAsStaticFramework = true 
    pod 'Firebase', :modular_headers => true
    pod 'FirebaseCore', :modular_headers => true
    pod 'FirebaseMessaging', :modular_headers => true
    # 其他Firebase依赖...
    
  3. 对ShareMenu Target中的RNShareMenu强制静态编译:
    target 'ShareMenu' do
        use_react_native!
        pod 'RNShareMenu', :path => '../node_modules/rn-rnf-share-menu'
        use_react_native!(
          :flipper_configuration => FlipperConfiguration.disabled, # 彻底禁用Flipper
        )
        # 新增静态编译处理
        pre_install do |installer|
          installer.pod_targets.each do |pod|
            if pod.name.eql?('RNShareMenu')
              def pod.build_type
                Pod::BuildType.static_library
              end
            end
          end
        end
      end
    
  4. 执行完整的Pods重置:
    pod deintegrate && pod cache clean --all && rm -rf ~/Library/Caches/CocoaPods && pod install
    

三、Xcode 项目配置检查

  • 在主Target的Build Settings中,确保Other Linker Flags包含-ObjC
  • 关闭Enable Bitcode(部分Firebase版本与Bitcode存在兼容性问题)
  • 确认Build Settings中的Framework Search Paths包含Pods的Frameworks目录

四、AppDelegate 代码修正

确保AppDelegate正确转发推送事件给RN Firebase:

#import <Firebase.h>
#import <RNFBApp/RNFBAppModule.h>
#import <RNFBMessaging/RNFBMessagingModule.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // 优先初始化Firebase
  [FIRApp configure];
  
  // 其他React Native初始化代码...
  
  return YES;
}

// 处理后台推送
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
                                                        fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  [[RNFBMessagingModule instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

// 处理App从推送启动的场景
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
  // 确保不拦截推送的打开逻辑
  return [RCTLinkingManager application:application openURL:url options:options];
}

五、代码层面试听逻辑校验

确保在App启动时尽早注册监听,且权限请求完成后再设置回调:

import messaging from '@react-native-firebase/messaging';

useEffect(() => {
  // 请求推送权限
  const requestPermission = async () => {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
      setupNotificationListeners();
    }
  };

  const setupNotificationListeners = () => {
    // 处理App在前台/后台时点击推送
    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log('Notification caused app to open from background state:', remoteMessage);
      // 跳转逻辑...
    });

    // 处理App从关闭状态点击推送启动
    messaging().getInitialNotification().then(remoteMessage => {
      if (remoteMessage) {
        console.log('Notification caused app to open from quit state:', remoteMessage);
        // 跳转逻辑...
      }
    });
  };

  requestPermission();

  return () => {
    // 清理监听(如果需要)
  };
}, []);

六、推送Payload 格式校验

确保推送Payload符合iOS规范,包含aps结构和必要的data字段:

{
  "notification": {
    "title": "测试推送",
    "body": "测试内容"
  },
  "data": {
    "screen": "Home",
    "id": "123"
  },
  "apns": {
    "payload": {
      "aps": {
        "content-available": 1
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者Naveen Appu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:44:59