实时数据库触发器和推送通知Firebase和iOS

问题描述 投票:2回答:1

我正在关注如何基于实时数据库触发器实现推送通知的GitHub代码。

这是代码和链接:

https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js

/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

/**
* Triggers when a user gets a new follower and sends a notification.
*
* Followers add a flag to `/followers/{followedUid}/{followerUid}`.
* Users save their device notification tokens to       `/users/{followedUid}/notificationTokens/{notificationToken}`.
*/
exports.sendFollowerNotification =    functions.database.ref('/followers/{followedUid}/{followerUid}').onWrite(event =>   {
const followerUid = event.params.followerUid;
const followedUid = event.params.followedUid;
// If un-follow we exit the function.
if (!event.data.val()) {
return console.log('User ', followerUid, 'un-followed user', followedUid);
}
console.log('We have a new follower UID:', followerUid, 'for user:',    followerUid);

// Get the list of device notification tokens.
const getDeviceTokensPromise =     admin.database().ref(`/users/${followedUid}/notificationTokens`).once('value');

// Get the follower profile.
const getFollowerProfilePromise = admin.auth().getUser(followerUid);

return Promise.all([getDeviceTokensPromise,    getFollowerProfilePromise]).then(results => {
const tokensSnapshot = results[0];
const follower = results[1];

// Check if there are any device tokens.
if (!tokensSnapshot.hasChildren()) {
  return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
console.log('Fetched follower profile', follower);

// Notification details.
const payload = {
  notification: {
    title: 'You have a new follower!',
    body: `${follower.displayName} is now following you.`,
    icon: follower.photoURL
  }
};

// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());

// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
      }
    }
  });
  return Promise.all(tokensToRemove);
});
});
});

我的愚蠢问题是函数和节点的新功能,在此代码中,通知会发送给所有保存令牌的用户,这是正确的吗?如果是这样我怎么能说只发送给一个特定的人呢?

我正在考虑在不同节点(子节点)中保存每个用户的令牌,以便我可以选择要向其发送通知的用户。它有用吗?

谢谢大家

ios node.js firebase firebase-cloud-messaging
1个回答
1
投票

此代码将仅向一个用户发送通知(在此示例中为关注者)。该用户可以有多个令牌,代表多个设备,因此变量名称为:tokensSnapshot。

您打算做什么是非常可行的云功能。例如,您只需要小心保存用户或令牌的节点路径。同样正如Frank van Puffelen建议的那样,熟悉Admin SDK(实时数据库和FCM)将真正帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.