【问题标题】:Cloud Functions Firestore Sending push notification to a specific userCloud Functions Firestore 向特定用户发送推送通知
【发布时间】:2020-05-26 15:09:45
【问题描述】:

我有聊天应用程序,我正在使用 Firebase firestore DB,我正在保存最近的消息,如下所示

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

接收方: 消息->recieverId->recent_messages

这意味着将向当前用户和接收用户文档写入相同的消息。 (相同的消息将被写入两个不同的文档)

消息内容如下:

- 发送方

 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 集合,只向接收用户发送通知有没有办法避免向他们俩发送推送通知?

【问题讨论】:

  • 您好,您可以在您的问题中添加云函数的代码吗?

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


【解决方案1】:

获取receiver用户的注册token:

// 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

【讨论】:

    猜你喜欢
    • 2017-10-08
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    相关资源
    最近更新 更多