Cloud Functions Firestore向特定用户发送推送通知

时间:2020-02-11 08:52:21

标签: firebase google-cloud-firestore google-cloud-functions firebase-cloud-messaging apple-push-notifications

我有聊天应用程序,我正在使用Firebase firestore DB,正在保存以下最新消息

发送方: 消息-> currentUserId->最近消息

接收方: 消息-> recieverId->最近消息

这意味着将同一条消息写入当前用户和接收方用户文档。 (同一封邮件将被写入两个不同的文档)

消息内容如下:

-发送方

 let fromData = ["text": text , "uid": toId, "userProfileUrl":  userAvatarUrl, "timestamp": Timestamp(date: Date()), "seen": false]

-接收方

 let toData = ["text": text  ,"uid": currentUserID, "userProfileUrl":  currentUser?.profileImageUrl ?? "", "timestamp": Timestamp(date: Date()),"seen": false] 

现在,我想观察recent_messages集合,仅向接收者用户发送通知。有什么办法避免向他们两个发送推送通知?

1 个答案:

答案 0 :(得分:1)

获取收件人用户的注册令牌:

// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(() => {
  messaging.getToken().then((refreshedToken) => {
    console.log('Token refreshed.');
    // Indicate that the new Instance ID token has not yet been sent to the
    // app server.
    setTokenSentToServer(false);
    // Send Instance ID token to app server.
    sendTokenToServer(refreshedToken);
    // ...
  }).catch((err) => {
    console.log('Unable to retrieve refreshed token ', err);
    showToken('Unable to retrieve refreshed token ', err);
  });
});

然后使用sendToDevice将通知发送给用户:

admin.messaging().sendToDevice(token_id, payload)
  .then(function(response) {

    console.log('Successfully sent:', response);
  })
  .catch(function(error) {
    console.log('Error sending:', error);
  });

您可以通过将令牌添加到数据库中来将其发送到服务器,然后在服务器端可以从数据库中读取并检索令牌。

https://firebase.google.com/docs/cloud-messaging/js/first-message

https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging.html#send-todevice