【发布时间】:2020-11-16 14:52:47
【问题描述】:
我是新手反应原生并创建一个应用程序,显示已存储在数据库中并使用 php 转换为 json 格式的事件列表。然后我使用 restful api 能够在我的 react native 应用程序中显示它们。
我想在每次添加新事件时显示背景通知。
经过一些研究,我发现发送后台通知的最佳方式是使用 firebase。当我从 Firebase 控制台运行测试通知时,我已经能够让我的代码在我的 iOS 设备上发送后台消息。
这是我的设置代码
const getFcmToken = async () => {
const fcmToken = await messaging().getToken();
if (fcmToken) {
console.log("Your Firebase Token is:", fcmToken);
} else {
console.log("Failed", "No Token Recived");
}
};
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);
}
};
async componentDidMount() {
await this.requestUserPermission();
// Register background handler
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('Messaage handled in the background!', remoteMessage);
});
};
}
在进行更多研究后,我发现无需使用 firebase 控制台即可发送通知的最佳方式是创建一个 RESTful API。
我遵循了有关如何执行此操作的在线教程,但不确定如何使其在后台运行,并且似乎没有任何教程。
这是我的代码。
export const sendPushNotifications = async () => {
const FIREBASE_API_KEY = "xxxxxxxxxx";
const message = {
registration_ids: [
"xxxxxxxxxx"
],
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,
},
data: {
title: "This is a Notification",
boby: "This is the body of the Notification",
score: 50,
wicket: 1,
},
}
let headers = new Headers({
"Content-Type" : "application/json",
Authorization: "key=" + FIREBASE_API_KEY,
})
let response = await fetch ("https://fcm.googleapis.com/fcm/send",{
method: "POST",
headers,
body: JSON.stringify(message),
})
response = await response.json();
console.log(response);
}
【问题讨论】:
标签: react-native firebase-cloud-messaging react-native-ios react-native-firebase react-native-push-notification