如何解决在本机反应中通过rest api进行通知
我正在尝试通过 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:',);
}
});
},[]);
return (
<View>
</View>
)
}
export default App;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。