Brad W
Brad W

Reputation: 2558

Why my ionic app FCMPlugin.onNotification() does not get called for incoming push notifications

I'm using cordova-plugin-fcm for handling push notification subscriptions and watching for incoming notifications.

This was all working when I set it up about a month ago. I still receive push notifications when the app is closed or in the background.

But if the app is in the foreground I get no notification. Which is actually fine because I was handling that with FCMPlugin.onNotification callback when everything was working.

And FCMPlugin.onNotification callback, success or error in my $ionPlatform.ready() never run no matter the state of the app.

Subscribe factory - Used in Rooms factory

myApp.factory('pushSubscribe', [
  '$firebaseArray',
  function ($firebaseArray) {
  return $firebaseArray.$extend({
    $$added: function(room){
      // Room topic is the $id of the chat room
      FCMPlugin.subscribeToTopic(room.key,
        function(success){
          //Success is being ran here with "OK" response
          //when a new chat room is added
        },
        function(error){
          // Not seeing any errors here
        }
      );
    },
    $$removed: function(room){
      FCMPlugin.unsubscribeFromTopic(room.key);
    }
  });
}]);

Rooms factory - registers chatters for push notifications

myApp.factory('Rooms', [
  '$firebaseArray',
  '$firebaseObject',
  'userService',
  'pushSubscribe',
  function ($firebaseArray, $firebaseObject, userService, pushSubscribe) {
  var ref = firebase.database().ref(),
      user = userService.getUser();
      userRoomsRef = firebase.database().ref('user-rooms').child(user.$id),
      roomsRef = firebase.database().ref('/rooms'),
      userRoom = new pushSubscribe(userRoomsRef);// Subscribes the current user to push notifications for all of their user-rooms
  return {
  // CRUD methods for rooms here
  }
}]);

app.js .run() - Supposed to listen for incoming notifications and handle them according to the state of the app but it isn't.

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
     FCMPlugin.onNotification(
       function(data){ //callback
         if(data.wasTapped){
           //Notification was received on device tray and tapped by the user.
           console.log( JSON.stringify(data) );
         } else {
           //Notification was received in foreground. Maybe the user needs to be notified.
           console.log( JSON.stringify(data) );
         }
       },
       function(msg){ //success handler
         console.log('onNotification callback successfully registered: ' + msg);
       },
       function(err){ //error handler
         console.log('Error registering onNotification callback: ' + err);
       }
     );
   });

node-gcm push router - Hosted on Heroku all chats hit routers url

var router = require('express').Router();
var firebase = require('firebase');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var gcm = require('node-gcm');
var sender = new gcm.Sender('MY_AUTH_TOKEN');

router.get('/', function(req, res){
  res.status(200).json({ message: 'GET route on router'});
});

router.post('/', jsonParser, function(req, res){
  firebase.auth().verifyIdToken(req.body.token)
  .then(function(user){
    var message = new gcm.Message({
      priority: 'high', 
      notification: {
        click_action: "FCM_PLUGIN_ACTIVITY",
        title: req.body.sender_name,
        body: req.body.message
      },
      data: {
        state: req.body.state,
        roomId: req.body.roomId,
        sender_imgUrl: req.body.sender_imgURL
      }
    });
    sender.send(message, { topic: req.body.topic }, function(err, response){
      if(err){
        res.status(500).json({ error: err });
      } else {
        res.status(200).json({ response: 'Push notification sent' });
      }
    });
  })
  .catch(function(err){
    res.status(500).json({ response: err });
  });
});

module.exports = router;

The send message method

$scope.sendMessage = function() {
        // Get the users auth jwt to verify them on the node router
        firebase.auth().currentUser.getToken(true)
        .then(function(userToken){
            $http({
                method: 'POST',
                url:'MY_HEROKU_HOSTED_NODE_ROUTER_URL',
                data:{ 
                    token: userToken,
                    message: $scope.IM.textMessage,
                    sender_name: $scope.user.name,
                    topic: '/topics/' + $state.params.roomId,
                    state: 'app.room',
                    roomId: $state.params.roomId,
                    sender_imgURL: $scope.user.pic,
                    chatters: chatters 
                }
            })
            .then(function(res){
                //Chats factory updates Firebase chat record
                Chats.send($scope.user, $scope.IM.textMessage);
                $scope.IM.textMessage = "";
            })
            .catch(function(err){
                debugger;
            });
        });
    };

Upvotes: 0

Views: 1125

Answers (0)

Related Questions