[英]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.
在做了一些研究之后,我觉得最好的方法是使用 firebase 云消息传递。
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.当我在 iOS 设备上运行我的应用程序时,我可以在终端中看到出现以下错误。
ReferenceError: Can't find variable: getFcmToken
参考错误:找不到变量: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.在实际使用之前声明
getFcmToken
。
// 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);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.