【问题标题】:Firebase Function - device token emptyFirebase 功能 - 设备令牌为空
【发布时间】:2018-02-21 06:57:39
【问题描述】:

我需要帮助,我整天都在寻找解决方案,但我无法解决我的问题,下面的代码不会读取设备令牌。

下面包含我的数据库结构。我设法收到了日志:'我们有一个新新闻要给你。'当我添加了一个新帖子但我收到了日志“没有通知令牌要发送到。 strong>" 这意味着即使已经存在设备令牌,它也无法检测到设备令牌。我做错了什么?

{

  "Newsv2" : {
"All" : {

  "-Ktr7ZkuChCjsUIMb_4f" : {
    "title" : "",
    "type" : "",
  }
},

 "Usersv2" : {

"h0RzzpdO7nZVLpAR4fi7xRWUqsT2" : {
  "device_token" : "",
  "name" : "",
  "user_no" : ""
}
  },
  
  }



/--News
    --All
       --name
       --desc

/--Usersv2
    --{userID}
      --device_token


exports.sendNotif = functions.database.ref('/Newsv2/All/{newsID}').onWrite(event => {
  const newsID = event.params.newsID;
  const userID = event.params.userID;

  if (!event.data.val()) {
    return console.log('News! ', newsID);
  }
  console.log('We have a new News for you!',newsID);

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

  return Promise.all([getDeviceTokensPromise]).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: 'Test Message',
        body: '',
        icon: ''
      }
    };

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

【问题讨论】:

  • 发布创建getDeviceTokensPromise的代码。什么时候运行?
  • 对不起,我忘了把它包括在内。 // 获取设备通知令牌列表。 const getDeviceTokensPromise = admin.database().ref(/users/${followedUid}/notificationTokens).once('value');
  • 您的数据库没有结构或包含您的代码期望的值。要获得更多帮助,您需要为失败的用户 ID 发布导出的 JSON(带有私有数据的占位符,例如令牌)。您可以从 Firebase 控制台进行导出。
  • { "Newsv2" : { "All" : { "-KtqNC3MTYcJEsAbE3QD" : { "title" : "type" : }, }, "Usersv2" : { "h0RzzpdO7nZVLpAR4fi7xRWUqsT2" : { "device_token" : "name" : ""user_no" : } }, } 是这个吗?
  • 您的代码期望device_token 有一个或多个孩子,其中每个孩子的关键是令牌。这不在您评论中的 JSON 中。此外,如果将 JSON 格式化并作为对您问题的编辑而不是作为评论包含在内,那么 JSON 将更具可读性。

标签: android node.js firebase firebase-realtime-database


【解决方案1】:

当用户注册或登录时,为了获取设备令牌,我将其存储在我的 firebase 数据库中。

    private DatabaseReference mUserDatabase;
    mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users/");
    //and if the login/register is successful
    mUserDatabase.child("device_token").setValue(deviceToken).addOnSuccessListener(new OnSuccessListener<Void>() {
                                                    @Override
                                                    public void onSuccess(Void aVoid) {
                                                    Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
                                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
                                                    application.startActivity(intent);
                                                }
                                            });

至于我的火力基地功能:

const deviceToken = admin.database().ref(`/Users/${unique_id}/device_token`).once('value');

【讨论】:

  • 你能再检查一下我编辑的问题吗?我之前忘记添加函数了。
猜你喜欢
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 2019-12-23
  • 2021-04-30
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多