简体   繁体   中英

Getting Firebase Cloud Messaging token in React Native

I am new to react native and I am trying to create an app that has background notifications. After doing some research I feel the best way to do this would be to use firebase cloud messaging.

After following a number of different tutorials I have written the following code.

 export default class App extends React.Component { requestUserPermission = async () => { const authStatus = await messaging().requestPermission(); const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL; if (enabled) { getFcmToken(); console.log('Authorization status:', authStatus); } }; getFcmToken = async () => { const fcmToken = await messaging().getToken(); if (fcmToken) { console.log(fcmToken); console.log("Your Firebase Token is:", fcmToken); } else { console.log("Failed", "No Token Recived"); } }; async componentDidMount() { await this.requestUserPermission(); // Register background handler messaging().setBackgroundMessageHandler(async (remoteMessage) => { console.log('Messaage handled in the background!', remoteMessage); }); }; }

When I run my app on my iOS device I can see within the terminal that I get the following error.

ReferenceError: Can't find variable: getFcmToken

When I try to send a test message it doesn't seem to appear.

My question is: Am I writing my code incorrectly or have I done something wrong?

Declare getFcmToken before you actually use it.

    // declare getFcmToken first
    const getFcmToken = async () => {
      const fcmToken = await messaging().getToken();
      if (fcmToken) {
          console.log(fcmToken);
          console.log("Your Firebase Token is:", fcmToken);
      } else {
          console.log("Failed", "No Token Recived");
      }
    };

    // then use it
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
      if (enabled) {
        getFcmToken();
        console.log('Authorization status:', authStatus);
      }
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM