首页
/ React Native Firebase 在 iOS 18 上的消息重复接收问题分析与解决方案

React Native Firebase 在 iOS 18 上的消息重复接收问题分析与解决方案

2025-05-19 23:36:32作者:虞亚竹Luna

问题现象

在使用 React Native Firebase 消息推送模块时,开发者发现在 iOS 18 系统上,onMessage 回调会被多次触发,导致同一消息被重复处理。这一问题在 iOS 17.5 及以下版本中不存在,仅出现在 iOS 18 设备上。

问题根源

经过开发者社区的深入讨论和分析,这个问题主要源于 iOS 18 系统本身的变更。在 iOS 18 中,系统会多次触发通知回调,特别是当应用处于前台时。具体表现为:

  1. 同一通知会被系统多次传递到应用层
  2. 每次传递的通知标识符(identifier)可能相同或仅有大小写差异
  3. 问题在 iOS 18.1 beta 版本中已被苹果修复

影响范围

  • 仅影响 iOS 18 系统设备
  • 影响所有使用 React Native Firebase 消息推送模块的应用
  • 主要出现在应用处于前台接收通知时

临时解决方案

在 iOS 18.1 正式版发布前,开发者可以采用以下几种临时解决方案:

方案一:消息 ID 去重

const lastMessageIdRef = useRef(null);

useEffect(() => {
  const unsubscribe = messaging().onMessage(async remoteMessage => {
    if (lastMessageIdRef.current === remoteMessage.messageId) return;
    
    lastMessageIdRef.current = remoteMessage.messageId;
    // 处理消息逻辑
  });

  return unsubscribe;
}, []);

方案二:原生层拦截

在 AppDelegate.m 中添加代码,通过比较通知标识符来过滤重复通知:

-(void)userNotificationCenter:(UNUserNotificationCenter *)center 
      willPresentNotification:(UNNotification *)notification 
        withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler 
{
  static NSString *lastNotificationId;
  
  if (![lastNotificationId isEqualToString:notification.request.identifier]) {
    // 处理新通知
    NSDictionary *userInfo = notification.request.content.userInfo;
    [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo
                                  fetchCompletionHandler:^void (UIBackgroundFetchResult result){}];
  }
  
  lastNotificationId = notification.request.identifier;
  completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

方案三:使用持久化存储

对于需要跨应用重启保持状态的场景,可以使用 MMKV 等持久化存储方案:

import { MMKV } from 'react-native-mmkv';

const storage = new MMKV({ id: 'notification-storage' });

messaging().onMessage(async message => {
  const messageId = message.messageId;
  const lastMessageId = storage.getString('lastMessageId');
  
  if (lastMessageId !== messageId) {
    storage.set('lastMessageId', messageId);
    // 处理新消息
  }
});

长期解决方案

随着 iOS 18.1 的发布,这个问题已在系统层面得到修复。建议开发者:

  1. 告知用户升级到 iOS 18.1 或更高版本
  2. 在应用中检测系统版本,仅对 iOS 18.0 应用临时解决方案
  3. 关注 React Native Firebase 官方更新,确保使用最新版本

最佳实践建议

  1. 消息处理逻辑应始终具备幂等性设计
  2. 重要业务逻辑不应仅依赖通知触发
  3. 考虑在服务端添加消息去重机制
  4. 对关键操作添加确认步骤,防止重复执行

总结

iOS 18 引入的消息重复问题给 React Native Firebase 开发者带来了挑战,但通过合理的临时解决方案和最终的系统修复,这个问题可以得到有效解决。开发者应根据自身应用特点选择合适的解决方案,并在系统更新后及时调整代码。

登录后查看全文
热门项目推荐
相关项目推荐