首页 > 解决方案 > Firebase FCM 没有被 onMessage() 捕获

问题描述

我在将 FCM 实施到我的反应本机应用程序中时遇到了麻烦。文档一点都不好,所以必须来这里寻求帮助。我设置了一个云功能,它将向给定的令牌发送通知。唯一的问题是,没有任何错误,并且该函数不发送通知。

云功能

exports.sendNotification = functions.https.onCall((fcmToken) => {
  console.log(fcmToken);
  console.log("in the func");
  const message = {
    notification: {
      title: "850",
      body: "2:45",
    },
    token: fcmToken,
  };

  // Send a message to the device corresponding to the provided
  // registration token.
  admin.messaging().send(message)
      .then((response) => {
      // Response is a message ID string.
        console.log("Successfully sent message:", response);
      })
      .catch((error) => {
        console.log("Error sending message:", error);
      });
  // See documentation on defining a message payload.
});

反应原生监听器

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

调用云函数

const token = await messaging().getToken()
functions()
  .httpsCallable('sendNotification')(token)
  .then(async (response) => {
    console.log(response)
  })
  .catch((error) => {
    console.log(error)
  })

标签: javascriptnode.jsfirebasereact-nativefirebase-cloud-messaging

解决方案


我认为你不应该在使用效果中使用它。

在 Appregistry 之前,我在 index.js 上使用它

import messaging from '@react-native-firebase/messaging';
async function onMessageReceived(message) {

 
  console.log("background message: " + JSON.stringify(message.data));
}
 messaging().onMessage(onMessageReceived);
 
function HeadlessCheck({ isHeadless }) {
  if (isHeadless) {
    // App has been launched in the background by iOS, ignore
    return null;
  }

  return <App />;
}



 AppRegistry.registerComponent(appName, () =>HeadlessCheck );

像那样


推荐阅读