如何使用Firebase管理员向设备发送通知

时间:2019-11-25 17:16:57

标签: node.js firebase-cloud-messaging firebase-admin

我正在为应用程序添加通知支持。我正在将React Native Firebase用于react native客户端,并且能够接收控制台发送的通知。

但是,当我使用firebase管理工具发送通知时,没有收到通知。

firebase管理员在服务器启动时初始化一次

    let admin = require('firebase-admin')

    let serviceAccount = require('../../appname-firebase-admin.json')

    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: 'https://appname-12e14.firebaseio.com',
    })
    console.log('initialise firebase admin')

然后我根据firebase管理员documentation

进行了此测试
async function sendNotification() {
  let admin = require('firebase-admin')

  let registrationToken =
    'super-long-token-goes-here'

  let message = {
    notification: { title: 'Super title', body: 'this is a test' },
    token: registrationToken,
  }

  admin
    .messaging()
    .send(message)
    .then(response => {
      // Response is a message ID string.
      console.log('Successfully sent notification:', response)
      return { success: true }
    })
    .catch(error => {
      console.log('Error sending notification:', error)
    })

  return {
    success: true,
  }
}

结果

Successfully sent notification: projects/appname-12e14/messages/0:1574700947563522%48f1ba652348f1ba99

在设备上没有通知。

编辑:我也尝试过使用.sendToDevice()

1 个答案:

答案 0 :(得分:1)

React-native-firebase确实会在打开的应用程序中显示通知,您可以创建自定义通知,并使用所需的组件在应用程序中显示通知。另外,您可以使用第三方服务(如Notify),该服务具有简单的API来管理它们。