创建 Expo dev 版本后出现错误:未创建 Firebase 应用程序“[DEFAULT]” - 调用 firebase.initializeApp()

问题描述 投票:0回答:1

我正在尝试通过将 Apple 推送通知服务 (APN) 与我的 iOS 应用程序中的 Firebase 云消息服务 (FCM) 链接起来,将推送通知合并到我的 Expo 应用程序中。我的理解是,最好在开发版本上测试此功能,因此我已将使用 EAS 完成的版本下载到我的 iPhone 上。构建成功,我可以尝试使用 expo dev 客户端在我的设备上运行它,但我不断在终端中收到错误消息:

Error: No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp()

我的

firebaseConfig
index.ts
文件中:

import { initializeApp } from "firebase/app"

// import { getAnalytics } from "expo-firebase-analytics"

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: process.env.FIREBASE_API_KEY,
  authDomain: process.env.FIREBASE_AUTH_DOMAIN,
  projectId: process.env.FIREBASE_PROJECT_ID,
  storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.FIREBASE_APP_ID,
  measurementId: process.env.FIREBASE_MEASUREMENT_ID,
}

// Initialize Firebase
export const startFirebase = () => initializeApp(firebaseConfig)

我正在从我的

startFirebase()
文件中调用
app.tsx
函数:

import "./i18n"
import "./utils/ignore-warnings"
import React, { useState, useEffect, useRef } from "react"
import { SafeAreaProvider, initialWindowMetrics } from "react-native-safe-area-context"
import { initFonts } from "./theme/fonts" // expo
import * as storage from "./utils/storage"
import { AppNavigator, useNavigationPersistence } from "./navigators"
import { RootStore, RootStoreProvider, setupRootStore } from "./models"
import { ErrorBoundary } from "./screens/error/error-boundary"
import { PersonaProvider } from "./context/PersonaContext"
import * as SplashScreen from "expo-splash-screen"
import { startFirebase } from "./services/firebase"
import { Alert, Platform } from "react-native"
import * as Notifications from "expo-notifications"
import messaging from "@react-native-firebase/messaging"

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
})

export const NAVIGATION_PERSISTENCE_KEY = "NAVIGATION_STATE"

function App() {

  const [rootStore, setRootStore] = useState<RootStore | undefined>(undefined)
  const {
    initialNavigationState,
    onNavigationStateChange,
    isRestored: isNavigationStateRestored,
  } = useNavigationPersistence(storage, NAVIGATION_PERSISTENCE_KEY)
  
  startFirebase()

  const requestUserPermission = async () => {
    const authStatus = await messaging().requestPermission()
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL

    if (enabled) {
      console.log("Authorization status:", authStatus)
    }
  }

  useEffect(() => {
    // const authStatus = async () =>  await messaging().requestPermission()
    if (requestUserPermission()) {
      // return fcm token from the device
      messaging()
        .getToken()
        .then((token) => {
          console.log("token received:", token)
        })
    } else {
      console.log("failed token status")
    }

    // Check whether an initial notification is available
    messaging()
      .getInitialNotification()
      .then(async (remoteMessage) => {
        if (remoteMessage) {
          console.log(
            "Notification caused app to open from quit state:",
            remoteMessage.notification,
          )
        }
      })

    // Assume a message-notification contains a "type" property in the data payload of the screen to open

    messaging().onNotificationOpenedApp((remoteMessage) => {
      console.log(
        "Notification caused app to open from background state:",
        remoteMessage.notification,
      )
      // navigation.navigate(remoteMessage.data.type);
    })

    // Register background handler
    messaging().setBackgroundMessageHandler(async (remoteMessage) => {
      console.log("Message handled in the background!", remoteMessage)
    })

    const unsubscribe = messaging().onMessage(async (remoteMessage) => {
      Alert.alert("A new FCM message arrived!", JSON.stringify(remoteMessage))
    })

    return unsubscribe
  }, [])



  // Kick off initial async loading actions, like loading fonts and RootStore
  useEffect(() => {
    async function prepare() {
      try {
        await SplashScreen.preventAutoHideAsync()
        await initFonts() // expo
        setupRootStore().then(setRootStore)
        await new Promise((resolve) => setTimeout(resolve, 2000))
      } catch (e) {
        console.warn(e)
      } finally {
        await SplashScreen.hideAsync()
      }
    }
    prepare()
  }, [])

  if (!rootStore || !isNavigationStateRestored) return null

  return (
    // <ToggleStorybook>
    <RootStoreProvider value={rootStore}>
      <SafeAreaProvider initialMetrics={initialWindowMetrics}>
        <ErrorBoundary catchErrors={"always"}>
          <PersonaProvider>
            <AppNavigator
              initialState={initialNavigationState}
              onStateChange={onNavigationStateChange}
            />
          </PersonaProvider>
        </ErrorBoundary>
      </SafeAreaProvider>
    </RootStoreProvider>
    // </ToggleStorybook>
  )
}

export default App

在我开始合并推送通知之前,这个应用程序也一直在使用 Firebase 实时数据库,并且一切正常。不知何故,我所做的更改导致了此错误。有人能为我解释一下吗?谢谢!

firebase expo firebase-cloud-messaging eas
1个回答
0
投票

你找到解决办法了吗?

© www.soinside.com 2019 - 2024. All rights reserved.