firebase - 通知反应原生聊天应用程序
问题描述
我实际上是在使用 react-native 的聊天应用程序上,并且我在 firebase 上有一个数据库。我想知道如何在应用程序上发布新消息时收到通知?那就是我生成消息的地方:
import * as types from './actionTypes'
import firebaseService from '../../services/firebase'
import Component from './app/components/AuthScreen/AuthTabs/BasicForm/Component.js'
const FIREBASE_REF_MESSAGES = firebaseService.database().ref('/GeneralMessage')
const FIREBASE_REF_MESSAGES_LIMIT = 20
export const sendMessage = message => {
return (dispatch) => {
dispatch(chatMessageLoading())
let currentUser = firebaseService.auth().currentUser
let createdAt = new Date().getTime()
let chatMessage = {
text: message,
createdAt: createdAt,
user: {
id: currentUser.uid,
email: currentUser.email,
}
}
FIREBASE_REF_MESSAGES.push().set(chatMessage, (error) => {
if (error) {
dispatch(chatMessageError(error.message))
} else {
dispatch(chatMessageSuccess())
}
})
}
}
export const updateMessage = text => {
return (dispatch) => {
dispatch(chatUpdateMessage(text))
}
}
export const loadMessages = () => {
return (dispatch) => {
FIREBASE_REF_MESSAGES.limitToLast(FIREBASE_REF_MESSAGES_LIMIT).on('value', (snapshot) => {
dispatch(loadMessagesSuccess(snapshot.val()))
}, (errorObject) => {
dispatch(loadMessagesError(errorObject.message))
})
}
}
解决方案
每当有新消息或数据库中有任何更改时,您都可以使用Firebase Cloud Function发送通知。
我在这里分享示例代码。
exports.sendNotification = functions.database.ref('/notificationRequests/{values}').onCreate((event) => {
// Grab the current value of what was written to the Realtime Database.
var itemVal = event.data.val()
// Notification details.
const payload = {
notification: {
title: itemVal.title,
body: itemVal.body,
sound: 'default',
},
data: {
otherData:"extra"
},
};
// Set the message as high priority and have it expire after 24 hours.
const options = {
contentAvailable: true,
priority: 'high',
timeToLive: 60 * 60 * 24,
};
if (itemVal.tokens) {
// Send a message to the device corresponding to the provided
// registration token with the provided options.
return admin.messaging().sendToDevice(itemVal.tokens, payload, options)
.then((response) => {
})
.catch((error) => {
console.log('Error : ', error);
});
} else {
}
});
参考链接:
Firebase 云函数
react-native-push-notifications-with-firebase-cloud- functions
https://aaronczichon.de/2017/03/13/firebase-cloud-functions/react-native-chat-app-serverless-firebase-
推送通知
推荐阅读
- javascript - 如何将行 ID 从 Flask 传递到 Modal?
- python - 每周更新我的应用程序的代码
- node.js - JS postgres - 错误的用户名连接
- c - 如何使用 OpenMP 并行遍历树
- wpf - 如何将我的组合框设置为 Office 2016 Telerik 版本?
- python - 从字典列表中删除重复项
- python - 如何计算非常小的数值的方差?
- groovy - Jmeter HTTP setPath - 我如何在 http 采样器中设置动态路径
- tensorflow - 如何在 TensorFlow 中进行预测?
- r - 重塑后 DataFrame 中的意外值