[英]Notification via rest api in react native
我正在嘗試通過 rest api 在 React Native 中發送通知。作為回應,我獲得了成功:1。 這里的問題是我沒有在模擬器中收到通知。
const token = await firebase.messaging().getToken();
console.log("token in sendNotification ",token)
const FIREBASE_API_KEY = "firebaseApiKey";
const message = {
to :token,
notification: {
title: "This is a Notification",
boby: "This is the body of the Notification",
vibrate: 1,
sound: 1,
show_in_foreground: true,
priority: "high",
content_available: true,
}
}
let headers = new Headers({
"Content-Type" : "application/json",
Authorization: "key=" + FIREBASE_API_KEY,
})
try {
let response = await fetch ("https://fcm.googleapis.com/fcm/send",{
method: "POST",
headers,
body: JSON.stringify(message),
})
response = await response.json();
console.log("response ", response);
} catch (error) {
console.log("error ", error);
}
https://firebase.google.com/docs/cloud-messaging/js/receive
您可以按照傳入的消息文檔進行操作
// Handle incoming messages. Called when:
// - a message is received while the app has a focus
// - the user clicks on an app notification created by a service worker
// `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});
在使用App.js的效果
import React,{useEffect} from 'react' import{View,Text} from 'react-native'; async function onDisplayNotification() { // Create a channel const channelId = await notifee.createChannel({ id: 'default', name: 'Default Channel', }); // Display a notification await notifee.displayNotification({ title: 'Notification Title', body: 'Main body content of the notification', android: { channelId, smallIcon: 'ic_launcher', // optional, defaults to 'ic_launcher'. }, }); } const App=()=> { useEffect(() => { // Assume a message-notification contains a "type" property in the data payload of the screen to open messaging().onMessage((payload) => { console.log('Message received. ', payload); onDisplayNotification(); //... }); messaging().onNotificationOpenedApp(remoteMessage => { console.log( 'Notification caused app to open from background state:', remoteMessage.notification, ); alert("Notification"); }); // Check whether an initial notification is available messaging().getInitialNotification().then(remoteMessage => { if (remoteMessage) { console.log( 'Notification caused app to open from quit state:', remoteMessage.notification, ); } }); }, []); return ( <View> </View> ) } export default App;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.