【问题标题】:FCM Keep token in syncFCM 保持令牌同步
【发布时间】:2022-01-18 01:37:34
【问题描述】:

所以我将 FCM 与我的 Xamarin.Forms 应用程序一起使用。我对如何保持我的应用程序中生成的令牌和存储在我的应用程序服务器中的令牌保持同步有点困惑。

步骤:

  1. 打开应用程序。
  2. OnTokenRefresh() 获取新令牌。
  3. 新令牌被发送到应用服务器。
  4. 应用服务器发送推送通知。

这很完美,除了有时,FCM 销毁令牌,应用程序未运行(第 2 步未触发),因此我的应用程序服务器无法再发送消息,因为不同步。

有没有办法将 FCM 令牌更新到我的应用服务器无需打开应用

【问题讨论】:

    标签: android xamarin firebase-cloud-messaging


    【解决方案1】:

    删除令牌的最佳方法是在您尝试使用它们发送消息时。届时,FCM API 会告诉您哪些令牌无效,您可以将它们从您的应用服务器中删除。

    您可以在functions-example repo for sending message through FCM 中找到代码示例:

    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) {
        functions.logger.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);
    

    因此,对于每个令牌,服务器都会返回 messaging/invalid-registration-tokenmessaging/registration-token-not-registered,此代码会从其数据库中删除该令牌。

    【讨论】:

    • 谢谢弗兰克,但从我的应用服务器中删除令牌不是问题。我已经这样做了,我删除了令牌,但是在用户打开应用程序之前我可以得到一个新的...所以,如果用户不打开应用程序,则令牌不会发送到我的应用程序服务器和用户不会收到任何新消息。
    • OnTokenRefresh 应该在应用未激活时触发,至少在 Android 上,因为它在服务中运行。
    • 好的,这应该是问题所在。我会检查!谢谢弗兰克!
    猜你喜欢
    • 2020-09-24
    • 2018-06-21
    • 2019-01-20
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多