我正在使用 Expo 开发 React Native 项目,并且在尝试在模拟器上检索 Expo 推送令牌时遇到了问题。我收到的错误如下:
LOG error [Error: Encountered an exception while calling native method: Exception occurred while executing exported method getDevicePushTokenAsync on module ExpoPushTokenManager: Default FirebaseApp is not initialized in this process com.app.development. Make sure to call FirebaseApp.initializeApp(Context) first.]
当我尝试使用 getExpoPushTokenAsync 方法将令牌记录到控制台时,会发生此错误。这是我的代码片段:
useEffect(() => {
async function configurePushNotifications() {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (finalStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
Alert.alert(
'Permission required',
'Push notifications need the appropriate permissions'
);
return;
}
const projectId = Constants.expoConfig?.extra?.eas.projectId;
try {
const token = await Notifications.getExpoPushTokenAsync({
projectId: projectId,
});
console.log('token', token);
} catch (error) {
console.error('error', error);
}
}
configurePushNotifications();
}, []);
我已将 google-services.json 添加到我的项目根目录,并相应地配置了 app.config.ts 文件。目前,我只在模拟器上测试它,因为我想控制台记录令牌。为什么我不断收到有关 FirebaseApp 未初始化的消息?
我将不胜感激任何解决此问题的见解或解决方案。谢谢!
我已经尝试过这里建议的方法,但没有成功: firebase.initializeApp() 与 FirebaseApp.initializeApp()
您看到的错误消息表明 Firebase 尚未初始化到您的应用程序。这是比使用任何 Firebase 服务(包括用于推送通知的 Firebase 云消息传递 (FCM))更早的重要一步。以下是解决问题的方法:
初始化 Firebase: 确保 Firebase 在实用程序开始时已初始化。这通常是在您的访问报告上完成的(与 App.Js 或 index.Js 一起)。以下是初始化 Firebase 的方法实例:
import * as Firebase from 'firebase';
import 'firebase/messaging';
// Your Firebase config object
const firebaseConfig = {
apiKey: 'PAPI-KEY',
authDomain: 'Auth-Domain',
databaseURL: 'Database-Url',
projectId: 'project-id',
storageBucket: 'storage-bucket',
messagingSenderId: 'messaging-sender-id',
appId: 'app-id',
};
// Initialize Firebase
if (Firebase.apps.length === 0) {
Firebase.initializeApp(firebaseConfig);
}
将 firebaseConfig 中的值替换为您的实际 Firebase 配置值。
检查配置文件: 仔细检查您的谷歌服务。 Json 报告有效地定位到您的项目根目录,并且 app.Config.Ts 记录已根据 Expo 文档正确配置。
使用真实设备: 虽然您提到要检查模拟器,但确实值得注意的是,Firebase 云消息传递 (FCM) 可能在模拟器上存在障碍或独一无二的行为。如果可行,请尝试检查实际工具以查看错误是否仍然存在。
查看 Firebase 和 Expo 版本: 确保您使用的是 Firebase 和 Expo 的兼容版本。有时,较新或较旧的版本可能存在已在不同版本中解决的问题。