通过FCM发送数据消息,

时间:2020-06-02 14:11:52

标签: swift firebase firebase-cloud-messaging apple-push-notifications

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

'我们有一个新的关注者UID:8dUMfYX9NibJDgOm3qdTcvtVO523,用户:FVa0Gy5KlVMLvipoWRRqsZ1CluF3'

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

'没有通知令牌可发送给'

我的想法是令牌未链接到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);
    });

1 个答案:

答案 0 :(得分:0)

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

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

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

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

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

相关问题