通过 FCM 发送数据消息,

Sending data messages through FCM,

我正在尝试通过 iOS 应用程序上的 Firebase 云消息传递向用户发送通知,当有人关注他们时,我在服务器上设置并部署了 javascript,它在这方面似乎很成功:

'We have a new follower UID: 8dUMfYX9NibJDgOm3qdTcvtVO523 for user: FVa0Gy5KlVMLvipoWRRqsZ1CluF3'.

出现在控制台日志中,这些是正确的 uid,但它也指出:

'There are no notification tokens to send to'.

我的想法是令牌没有链接到 auth 帐户,但我不确定如何或在什么时候应该。我还应该注意,我已经连接到应用程序委托中的 fcm 并使用以下命令收到了一个令牌:

InstanceID.instanceID().instanceID { (result, error) in
  if let error = error {
    print("Error fetching remote instange ID: \(error)")
  }
  else {
    print("FCM Token = \(String(describing: result?.token))")
    print("Remote instance ID token: \(result!.token)")

//     self.instanceIDTokenMessage.text  = "Remote InstanceID token: \(result.token)"
  }
}

这是 javascript:

'use strict';

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

/**
 * 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('/users/{followerUid}/following/{followedUid}')
    .onWrite(async (change, context) => {
      const followerUid = context.params.followerUid;
      const followedUid = context.params.followedUid;
      // If un-follow we exit the function.
      if (!change.after.val()) {
        return console.log('User ', followerUid, 'un-followed user', followedUid);
      }
      console.log('We have a new follower UID:', followerUid, 'for user:', followedUid);

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

      // The snapshot to the user's tokens.
      let tokensSnapshot;

      // The array containing all the user's tokens.
      let tokens;

      const results = await Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]);
      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: `${followerUid.name} is now following you.`
        }
      };

      // Listing all tokens as an array.
      tokens = Object.keys(tokensSnapshot.val());
      // Send notifications to all tokens.
      const response = await admin.messaging().sendToDevice(tokens, payload);
      // 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);
    });

我找到了答案,javascript 的部分说:

const getDeviceTokensPromise = admin.database().ref(`/users/${followedUid}/notificationTokens`).once('value');

需要以以下格式连接到数据库:

users:{
   $user_id:{
      notificationTokens:{
            $token: true
         }
   }
}

为了访问令牌,因为可以有多个用户登录实例,我之前将密钥 'notificationTokens' 的值设置为令牌 - 这就是它不起作用的原因。