iOS平台React Native中Firebase Messaging的RNFBMessagingSerializer崩溃问题
React Native iOS集成Firebase Messaging崩溃解决方案
崩溃原因
崩溃发生在[RNFBMessagingSerializer remoteMessageUserInfoToDict:]方法,错误-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance,本质是推送payload中某个字段的类型与RNFBMessagingSerializer预期不符——比如服务器将本该是字符串的字段传成了数字,导致序列化时调用了错误的字符串处理方法。
解决步骤
1. 检查并修正服务器推送Payload
- 核对FCM推送的
data及aps字段,确保所有字段类型与客户端预期一致:- 若客户端代码中按字符串处理某个字段,服务器不能传数字类型;
- 重点排查自定义数据字段,以及
aps里的alert等文本字段(badge字段应为数字,无需修改)。
2. 临时修复RNFBMessagingSerializer代码
找到node_modules/@react-native-firebase/messaging/ios/RNFBMessagingSerializer.m文件,定位到崩溃的第108行,补充类型判断逻辑:
// 原代码未做类型检查直接调用字符串方法,修改为: id value = userInfo[key]; // 若需判断字符串相等,先检查类型 if ([value isKindOfClass:[NSString class]] && [value isEqualToString:@"目标字符串"]) { // 原有业务逻辑 } // 若需将数字转字符串,先执行转换 if ([value isKindOfClass:[NSNumber class]]) { value = [value stringValue]; } // 后续处理逻辑
注意:此为临时方案,升级库后需重新确认,建议优先升级库或修正服务器Payload。
3. 升级React Native Firebase Messaging库
该问题大概率是旧版本的类型判断Bug,升级到最新稳定版即可解决:
# npm 升级 npm install @react-native-firebase/messaging@latest --save # yarn 升级 yarn add @react-native-firebase/messaging@latest
升级后重新执行iOS依赖安装:
cd ios && pod install && cd ..
4. 本地拦截修正Payload(服务器无法临时修改时)
在iOS原生代码中拦截推送消息,修正字段类型后再传递给RN处理:
在AppDelegate.m中实现或修改UNUserNotificationCenterDelegate的处理方法:
#import <React/RCTBridge.h> #import <FirebaseMessaging/RNFBMessagingUNUserNotificationCenter.h> - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { // 复制可变的userInfo NSMutableDictionary *mutableUserInfo = [response.notification.request.content.userInfo mutableCopy]; // 遍历修正所有数字类型为字符串 for (NSString *key in mutableUserInfo) { id value = mutableUserInfo[key]; if ([value isKindOfClass:[NSNumber class]]) { mutableUserInfo[key] = [value stringValue]; } } // 创建修正后的通知请求 UNMutableNotificationContent *modifiedContent = [response.notification.request.content mutableCopy]; modifiedContent.userInfo = mutableUserInfo; UNNotificationRequest *modifiedRequest = [UNNotificationRequest requestWithIdentifier:response.notification.request.identifier content:modifiedContent trigger:response.notification.request.trigger]; // 调用RN Firebase的原处理逻辑 UNNotificationResponse *modifiedResponse = [UNNotificationResponse responseWithNotificationRequest:modifiedRequest actionIdentifier:response.actionIdentifier origin:response.origin]; [[RNFBMessagingUNUserNotificationCenter sharedInstance] userNotificationCenter:center didReceiveNotificationResponse:modifiedResponse withCompletionHandler:completionHandler]; }
内容的提问来源于stack exchange,提问作者vikas shah
相关产品推荐
相关产品推荐

