据我所知,我已经配置了react-native使用一些文档。当选择整个应用作为目标时,react native应用会正确地接收通知。但是,当通过主题从火基控制台发送时,我无法获得相同的结果。我做错了什么?提前感谢
通过app作为目标接收通知的屏幕截图。[1]: https://i.stack.imgur.com/8huVS.png
PushNotifHelper
import messaging from '@react-native-firebase/messaging';
const TOPIC = 'patient-topic';
export const requestUserPermission = async () => {
//On ios,checking permission before sending and receiving messages
const authStatus = await messaging().requestPermission();
return (
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL
);
};
export const getFcmToken = () => {
// Returns an FCM token for this device
messaging()
.getToken()
.then(fcmToken => {
console.log('FCM Token -> ', fcmToken);
});
};
export const receiveNotificationFromQuitState = () => {
messaging()
.getInitialNotification()
.then(async remoteMessage => {
if (remoteMessage) {
console.log(
'getInitialNotification:' +
'Notification caused app to open from quit state',
);
}
});
};
export const receiveBackgroundNotification = () => {
messaging().onNotificationOpenedApp(async remoteMessage => {
if (remoteMessage) {
console.log(
'onNotificationOpenedApp: ' +
'Notification caused app to open from background state',
);
}
});
};
//stop listening for new messages.
export const unsubscribeDeviceTopic = messaging().onMessage(
async remoteMessage => {
console.log('New notification arrived' + JSON.stringify(remoteMessage));
},
);
export const backgroundThread = () => {
//It's called when the app is in the background or terminated
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Background notification' + JSON.stringify(remoteMessage));
});
};
export const subscribeTopicToGetNotification = () => {
/**
* based on Topic, FCM server to send targeted
* messages to only those devices subscribed to that topic
*/
messaging()
.subscribeToTopic(TOPIC)
.then(() => {
console.log(`Topic: ${TOPIC} Suscribed`);
});
};
在useEffect内部初始化
useEffect(() => {
async function setupPatientNotification() {
if (await requestUserPermission()) {
getFcmToken();
} else {
console.log('Not Authorization status');
}
}
receiveNotificationFromQuitState();
receiveBackgroundNotification();
subscribeTopicToGetNotification();
backgroundThread();
return () => {
unsubscribeDeviceTopic;
// messaging().unsubscribeFromTopic(TOPIC);
};
}, []);
我也面临同样的问题,因为我有一个单独的订阅主题,而没有等待从Firebase检索令牌。
我认为您需要在系统获得Fcm令牌或授权通知权限后移动到订阅主题。
这是我的代码的一个例子,现在它可以正常工作了
useEffect(() => {
(async () => {
await createChannelId();
const authorizationStatus = await requestUserPermission();
await messaging().registerDeviceForRemoteMessages();
if (authorizationStatus) {
const fcmToken = await messaging().getToken();
setItem(FCM_TOKEN, fcmToken);
subscribeTopic(NotificationTopics.ApplicationUpdate);
}
})();
}, []);