推送通知Firebase

时间:2018-01-26 13:27:57

标签: firebase ionic2 firebase-cloud-messaging ionic3 ionic-native

我有一个实时聊天firebase,并希望在用户之间发送的每条消息都实现通知,但是我还没有找到如何执行此操作

1 个答案:

答案 0 :(得分:2)

在数据库上执行写操作时必须使用firebase函数

从Google

结帐codelab
exports.sendNotifications = functions.database.ref('/messages/{messageId}').onCreate(event => {
  const snapshot = event.data;

  // Notification details.
  const text = snapshot.val().text;
  const payload = {
    notification: {
      title: `${snapshot.val().name} posted ${text ? 'a message' : 'an image'}`,
      body: text ? (text.length <= 100 ? text : text.substring(0, 97) + '...') : '',
      icon: snapshot.val().photoUrl || '/images/profile_placeholder.png',
      click_action: `https://${functions.config().firebase.authDomain}`
    }
  };

  // Get the list of device tokens.
  return admin.database().ref('fcmTokens').once('value').then(allTokens => {
    if (allTokens.val()) {
      // Listing all tokens.
      const tokens = Object.keys(allTokens.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(allTokens.ref.child(tokens[index]).remove());
            }
          }
        });
        return Promise.all(tokensToRemove);
      });
    }
  });
});

在此片段firebase函数中创建,以便在生成函数体通知有效内容时发生写操作,并使用admin.messaging().sendToDevice()方法向用户列表发送通知