php - 使用 firebase 和 php 反应原生后台通知
问题描述
我是本机反应的新手,并创建了一个应用程序,该应用程序显示存储在 mysql 数据库中并使用 php 转换为 json 的事件列表。然后将事件列表显示在 react native flatlist 中。
每次将事件添加到平面列表时,我都希望收到背景通知。在做了一些研究之后,我发现发送后台通知的最佳方式是使用 firebase。我能够设置后台通知,然后从 firebase 控制台发送。
这是我的代码。
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();
fetch('http://ad9e61f2797a.ngrok.io/Notifications.php');
// Register background handler
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('Messaage handled in the background!', remoteMessage);
});
// When app is in the background and clicked
messaging().onNotificationOpenedApp(async (remoteMessage) => {
console.log('Notification caused app to open from background state:', remoteMessage.notification);
});
// when app is in closed and clicked
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log('Notifivation caused app to open from closed state:', remoteMessage.notification);
}
});
};
)
我希望我的通知无需使用 firebase cconsole 即可发送。我已经创建了 php 服务器代码来尝试执行此操作,但我似乎无法显示通知。
这是我的php代码
<?php
$url = "https://fcm.googleapis.com/fcm/send";
$token = "xxxxxxxx";
$serverKey = 'xxxxxxxxx';
$title = "Title";
$body = "Body of the message";
$notification = array('title' => $title, 'text' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification, 'priority' => 'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key=' . $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
// Send the request
$response = curl_exec($ch);
// Close request
if ($response === FALSE) {
die('FCM Send Error: ' , curl_errno($ch));
}
curl_close($ch);
?>
我正在尝试在我的 iPhone 上运行我的应用程序。
解决方案
推荐阅读
- c - C:内存地址数组?
- javascript - 无法弄清楚这个带有 2 个函数和一个 || 的 onClick 处理程序是什么 ( OR ) 运算符
- python - 在pygame中单击重叠的矩形
- performance - 使用 T-SQL 中的单个查询的 FIFO 库存老化报告
- powerbi - 完成所有 10 门课程的独特学生人数
- tensorflow - 我希望我的神经网络输出为 0 或 1,而不是 0 和 1 之间的概率,在输出层具有自定义阶跃函数
- javascript - 如何将 JavaScript 日期转换为 PostgreSQL 时间(无时区)?
- azure - 有什么方法可以查看 Azure 负载均衡器的访问日志
- r - 如何使用 ggplot 在数据框中绘制特定行
- swift - 未设置 Swift 包清单属性“defaultLocalization”