【问题标题】:How can I send Firebase notifications using cloudfunctions on firebase database datachange? [closed]如何在 Firebase 数据库数据更改时使用云功能发送 Firebase 通知? [关闭]
【发布时间】:2019-03-31 02:10:11
【问题描述】:

如果 firebase 数据库值发生更改,我正在尝试创建云功能,然后我发送 firebase 通知?下面是我的 firebase 数据库快照...就像我想发送有关 liveurl 更改的通知

livestream
    |_ 
      liveurl: "https://www.youtube.com/watch?v=Z8agqyGIaD8"

【问题讨论】:

    标签: android firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions


    【解决方案1】:

    这是云功能和云消息传递用例的主要示例。事实上,类似的场景在What can I do with Cloud Functions? 文档的Notify users when something interesting happens 部分下进行了介绍:

    1. 该函数在写入存储关注者的实时数据库路径时触发。
    2. 该函数编写要通过 FCM 发送的消息。
    3. FCM 将通知消息发送到用户的设备。

    为此还有一个FCM Notifications quickstart sample available on GitHub

    作为一个简单的示例,您可以编写一个云函数来执行此操作,例如:

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    exports.liveUrlChange = functions.database.ref('/livestream/liveurl').onWrite((event) => {
        // Exit if data is deleted.
        if (!change.after.exists()) return null;
    
        // Grab the current value of what was written to the Realtime Database.
        const value = change.after.val();
        console.log('The liveurl value is now', value);
    
        // Build the messaging notification, sending to the 'all' topic.
        var message = {
            notification: {
                title: 'Database change',
                body: 'The liveurl value has changed to ' + value
            },
            topic: 'liveurl_changed'
        };
    
        // Send the message.
        return admin.messaging().send(message)
            .then((message) => {
                console.log('Successfully sent message:', message);
            })
            .catch((error) => {
                console.error('Error sending message:', error);
            });
    });
    

    这是一个Cloud Functions 方法,它将对数据库中/livestream/liveurl 节点的更改做出反应,并使用云消息传递给send a message to a topic(即liveurl_changed)。

    为了使其正常工作,您需要:

    1. Deploy this function to Cloud Functions
    2. Setup Cloud Messaging in your app
    3. Subscribe the client app to the liveurl_changed topic

    【讨论】:

      【解决方案2】:

      试试这个云功能:

      exports.sendNotification = functions.database.ref('/livestream/{liveurl}').onUpdate((data, context) => {
      
      const liveurl = context.params.liveurl;
      
      //getting the instance of the target user. this instance object will contain the device token of the target user
      return admin.database().ref(`/apps/${app_id}/users/${sender_id}/instances`).once('value').then(function(instancesIdAsObj) {
      
          const tokens = Object.keys(instancesIdAsObj.val());
      
          const payload = {
              notification: {
              title: sender_fullname,
              body: text,
              icon : "ic_notification_small",
              sound : "default",
              click_action: "NEW_MESSAGE",
              "content_available": "true",
              badge : "1"
          },
      
              data: {
                  liveurlString: liveurl,
              }
          };
      
          return admin.messaging().sendToDevice(tokens, payload).then(function (response) {
              console.log("Push notification for message "+ JSON.stringify(message) + " with payload "+ JSON.stringify(payload) +" sent with response ",  JSON.stringify(response));
      
                      return error;
                  }
              });
      
          })
          .catch(function (error) {
              console.log("Error sending message:", error);
              return 0;
          });
      
      });
      

      });

      【讨论】:

        猜你喜欢
        • 2017-10-24
        • 1970-01-01
        • 2019-02-23
        • 2018-06-01
        • 2019-10-12
        • 1970-01-01
        • 2017-10-26
        • 2021-04-04
        • 1970-01-01
        相关资源
        最近更新 更多