【问题标题】:Cloud Functions for Firebase - Send FCM message to multiple tokensCloud Functions for Firebase - 向多个令牌发送 FCM 消息
【发布时间】:2018-11-04 13:44:53
【问题描述】:

在我的实时数据库中创建节点时,我必须向多个令牌发送消息。
我使用那个代码,但是任何通知都丢失了(人们没有收到它)。

 exports.sendMessage = functions.database.ref('/messages/{messageId}')
.onCreate((snapshot, context) => {
 const original = snapshot.val();

 let msg = {
    message: {
        data: {
            title: 'title2 test',
            body: 'body2 test',
            notify_type: 'chat_message',
            notify_id: ((new Date()).getTime()).toString(),
        },
        apns: {
            headers: {
                'apns-priority': '10',
                'apns-expiration': '0'
            },
            payload: {
                aps: { contentAvailable: true, sound:'' },
                'acme1': 'bar',
                title: 'title test',
                body: 'body test',
                notify_type: 'chat_message',
                notify_id: ((new Date()).getTime()).toString()
            }
        },
        token: token
    }
};

 var query = firebase.database().ref("users");
 return query.once("value")
      .then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
          var user = childSnapshot.val();
          var token = user.token;
          var username = user.username;
          msg.message.token = token;
          admin.messaging().send(msg.message).then((response) => {
                console.log('message sent to '+username);
            }).catch((error) => {
                console.log(error);
            });              
      });
    });
});

“回报”承诺正确吗?我想我必须等待所有的“admin.messagging() Promise,但我不知道我该怎么做。

非常感谢。

【问题讨论】:

  • admin.messaging().send() 返回一个承诺。你需要注意这些。
  • 最好的方法是“返回”所有的 Promise,但我该怎么做呢? Promise.all() 可以解决吗?
  • 如果您不确定,可以通过此视频系列了解 Promise。 youtube.com/watch?v=7IkUgCLr5oA

标签: javascript firebase firebase-cloud-messaging google-cloud-functions firebase-admin


【解决方案1】:

您可以向一组令牌发送通知。我正在使用此代码发送通知

return admin.messaging().sendToDevice(deviceTokenArray, payload, options).then(response => {
  console.log("Message successfully sent : " + response.successCount)
  console.log("Message unsuccessfully sent : " + response.failureCount)
});

我想你可以在这里找到更多信息 https://firebase.google.com/docs/cloud-messaging/admin/legacy-fcm

【讨论】:

  • 我从 API 读取它,但我无法发送静默通知设置 apn 标头。对吗?
  • 我不明白你想要达到什么目的。您的问题与向多个令牌发送通知无关?对于静音通知设置。您是否尝试过发送没有声场的数据字段?
  • 我必须向多个令牌发送通知,但要设置 APN 标头。无声通知不是没有声音的通知,而是针对后台应用的。
【解决方案2】:

这是您将 FCM 发送到令牌数组的方式:

  return Promise.all([admin.database().ref(`/users/${user}/account/tokensArray`).once('value')]).then(results => {
    const tokens = results[0];
    if (!tokens.hasChildren()) return null;
    let payload = {
      notification: {
        title: 'title',
        body: 'message',
        icon: 'icon-192x192.png'
      }
    };
    const tokensList = Object.keys(tokens.val());
    return admin.messaging().sendToDevice(tokensList, payload);
  });

【讨论】:

  • 这不是静默通知,我必须设置 APNS 标头.....如何使用“sendToDevice()”?
【解决方案3】:

要为所有发送操作返回一个 Promise,请将您的代码修改为:

 return query.once("value")
      .then(function(snapshot) {
        var allPromises = [];
        snapshot.forEach(function(childSnapshot) {
          var user = childSnapshot.val();
          var token = user.token;
          var username = user.username;
          msg.message.token = token;
          const promise = admin.messaging().send(msg.message).then((response) => {
                console.log('message sent to '+username);
            }).catch((error) => {
                console.log(error);
            });
          allPromises.push(promise);              
      });
      return Promise.all(allPromises);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多