如何向通知FCM ionic3添加按钮

时间:2018-06-01 07:23:17

标签: firebase ionic3 firebase-cloud-messaging

我正在尝试使用ionic3使用FCM(firebase云消息)插件向我的推送通知添加三个按钮。推送通知在没有操作按钮的情况下工作,但是当我尝试实现它们时,我在firebase功能控制台中出现错误。我读了很多关于toppic的问题,但没有人帮我解决这个问题。

这是我的组件代码(没有尝试实现动作按钮,因为这些代码不起作用,这个代码没有,但后来没有显示按钮):

        firebase.auth().onAuthStateChanged(this.onAuthStateChanged.bind(this));

}

onAuthStateChanged(user) {
  console.log('user', user)
  if (user && this.currentUid === user.uid) {
    return;
  }

  this.platform.ready().then(() => {
    if(!this.platform.is('cordova')) return;

   this.fcm.subscribeToTopic('all');


   if(user){
    this.saveToken();
    this.currentUid = user.uid;
   }
   this.fcm.onNotification().subscribe(data => {

    // alert('message received: ' + data.aps.alert.body);

     if(data.wasTapped) {
     // alert("Received in background");
     } else {
     // alert("Received in foreground");
     };
   });
   this.fcm.onTokenRefresh().subscribe(token => {
     // backend.registerToken(token);
     this.saveToken();
   });
  });
}

saveToken() {
  this.fcm.getToken().then(currentToken => {
    // backend.registerToken(token);
    if (currentToken) {
      firebase.database().ref('users/' + this.currentUid + '/notificationTokens/' + currentToken).set(true);
     // alert('save token: users/' + this.currentUid + '/notificationTokens/' + currentToken)
    }
  }).catch(err => {
    console.error('Unable to get messaging token.', err);
    if (err.code === 'messaging/permission-default') {
     console.log('You have not enabled notifications on this browser. To enable notifications reload the page and allow notifications using the permission dialog.');
    } else if (err.code === 'messaging/notifications-blocked') {
     console.log('You have blocked notifications');
    }
  })
}

这是我的firebase云功能:

exports.sendChatNotification = functions.database.ref('/app/chat/user/{clientUid}/{trainerUid}/{pushId}').onWrite((event) => {
  const clientUid = event.params.clientUid;
  const trainerUid = event.params.trainerUid;
  const MessageId = event.params.pushId;
  const Message = event.data.val();

  console.log('newly pushed message -> ', Message)
  // If un-follow we exit the function.
  if (!event.data.val()) {
    return console.log('Client ', clientUid, 'un-followed user', trainerUid);
  }
  console.log('We have a new message of trainer with UID:', trainerUid, 'voor client veranderd nu wel?:', clientUid);
  console.log('message en id', Message, MessageId);
  // Get the list of device notification tokens.
  const getDeviceTokensPromise = admin.database().ref(`/users/${(Message.afzender === 'pt') ? clientUid : trainerUid}/notificationTokens`).once('value'); // deelnemer krijgt notificatie van trainer

  console.log(`/users/${clientUid}/notificationTokens`);
  // Get the trainer profile.
  const getTrainerProfilePromise = admin.auth().getUser(trainerUid);

  return Promise.all([getDeviceTokensPromise, getTrainerProfilePromise]).then((results) => {
    const tokensSnapshot = results[0];
    const trainer = 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.');

    // Notification details.
    const payload = {
      notification:{
        title: `Nieuw bericht ${(Message.afzender === 'pt') ? 'van de trainer' : 'van een client'}!`,
        body: `${Message.naam} heeft je een bericht gestuurd.`,
        sound: "default",
        click_action: "FCM_PLUGIN_ACTIVITY",
        icon: "fcm_push_icon",
        // actions: [
        //   {
        //     icon: 'emailGuests',
        //     title: 'EMAIL GUESTS',
        //     callback: 'emailGuests',
        //     foreground: true
        //   },
        //   { icon: 'snooze', title: 'SNOOZE', callback: 'snooze', foreground: false }
        // ],
      // "data":{
      //   "actions": [
      //     { "icon": "emailGuests", "title": "EMAIL GUESTS", "callback": "emailGuests", "foreground": true},
      //     { "icon": "snooze", "title": "SNOOZE", "callback": "snooze", "foreground": false}
      //   ]
      // },
        to:"/topics/topicExample",
        priority:"high"
        // "restricted_package_name":""
      }
  };

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

0 个答案:

没有答案