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

Expo SDK 50集成Firebase Cloud Messaging (FCM)报错求助

Expo SDK 50 集成 Firebase Cloud Messaging (FCM) 报错解决方案

问题背景

在 Expo SDK 48 中可正常集成 Firebase Cloud Messaging (FCM),无任何问题;升级至 Expo SDK 50 后,使用 FCM 时出现报错,需完成 SDK 50 与 FCM 的正确集成。

相关文件参考:

  • App.js
  • app.json
  • package.json
  • 错误信息

解决方案步骤

1. 安装适配版本的依赖包

SDK 50 对 Firebase 相关包有版本兼容要求,执行以下命令安装对应版本:

npm install expo-firebase-messaging@~11.8.0 firebase@^10.11.0 expo-notifications@~0.27.6
# 或使用 yarn
yarn add expo-firebase-messaging@~11.8.0 firebase@^10.11.0 expo-notifications@~0.27.6

版本号需严格匹配 Expo SDK 50 官方兼容列表,避免版本不兼容导致的底层报错

2. 配置 app.json 核心参数

确保在 app.json 中正确配置 Firebase 配置文件路径、平台权限及插件参数:

{
  "expo": {
    "android": {
      "googleServicesFile": "./google-services.json",
      "permissions": [
        "RECEIVE_BOOT_COMPLETED",
        "POST_NOTIFICATIONS"
      ]
    },
    "ios": {
      "googleServicesFile": "./GoogleService-Info.plist",
      "infoPlist": {
        "UIBackgroundModes": ["remote-notification"],
        "NSUserNotificationUsageDescription": "需要通知权限接收消息"
      }
    },
    "plugins": [
      [
        "expo-firebase-messaging",
        {
          "messagingPermission": "Allow notifications",
          "iosRemoteNotificationMode": ["alert", "badge", "sound"]
        }
      ]
    ]
  }
}

注意:googleServicesFile 路径需指向项目根目录下的 Firebase 配置文件,iOS 必须开启 remote-notification 后台模式

3. 修正 App.js 中的 FCM 逻辑

SDK 50 中需配合 expo-notifications 处理通知展示,调整后的初始化及监听代码如下:

import { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import * as Notifications from 'expo-notifications';
import * as FirebaseMessaging from 'expo-firebase-messaging';
import { initializeApp } from 'firebase/app';

// 初始化 Firebase
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};
initializeApp(firebaseConfig);

// 设置通知处理规则
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

export default function App() {
  const [fcmToken, setFcmToken] = useState('');
  const [receivedNotification, setReceivedNotification] = useState(null);

  useEffect(() => {
    async function setupFCM() {
      // 请求通知权限
      const { status } = await Notifications.requestPermissionsAsync();
      if (status !== 'granted') {
        alert('请开启通知权限以接收FCM消息');
        return;
      }

      // 获取FCM令牌
      const token = await FirebaseMessaging.getToken();
      setFcmToken(token);
      console.log('FCM Token:', token);
    }

    // 监听前台通知接收
    const notificationListener = Notifications.addNotificationReceivedListener(notification => {
      setReceivedNotification(notification);
    });

    // 监听通知点击事件
    const responseListener = Notifications.addNotificationResponseReceivedListener(response => {
      console.log('Notification clicked:', response);
    });

    setupFCM();

    // 清理监听
    return () => {
      Notifications.removeNotificationSubscription(notificationListener);
      Notifications.removeNotificationSubscription(responseListener);
    };
  }, []);

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 }}>
      <Text style={{ marginBottom: 15 }}>FCM Token: {fcmToken || '未获取'}</Text>
      {receivedNotification && (
        <Text style={{ marginTop: 10 }}>
          收到通知: {JSON.stringify(receivedNotification.request.content.title)}
        </Text>
      )}
    </View>
  );
}

4. 针对性排查常见报错

根据你遇到的错误信息,对应处理:

  • "No Firebase App '[DEFAULT]' has been created":检查 Firebase 初始化代码是否放在 App 组件渲染前,确保配置参数与 Firebase 后台一致
  • Android 通知不显示:确认 google-services.json 放置路径正确,且已添加 POST_NOTIFICATIONS 权限;测试前需重新构建 Android 项目
  • iOS 通知不显示:验证 Apple Developer 后台已配置推送证书,GoogleService-Info.plist 中的 APNS_ENVIRONMENT 与当前环境匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:25:33