Почему мое ионное приложение FCMPlugin.onNotification() не вызывается для входящих push-уведомлений

Я использую cordova-plugin-fcm для обработки подписок на push-уведомления и отслеживания входящих уведомлений.

Это все работало, когда я установил его около месяца назад. Я все еще получаю push-уведомления, когда приложение закрыто или в фоновом режиме.

Но если приложение находится на переднем плане, я не получаю уведомления. Что на самом деле хорошо, потому что я справился с этим FCMPlugin.onNotification обратный звонок, когда все работало.

А также FCMPlugin.onNotification обратный вызов, успех или ошибка в моем $ionPlatform.ready() Никогда не запускайте, независимо от состояния приложения.

Подписаться фабрика - Используется в фабрике комнат

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

Фабрика комнат - регистрирует чаты для push-уведомлений

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() - Предполагается, что прослушивает входящие уведомления и обрабатывает их в соответствии с состоянием приложения, но это не так.

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

push-маршрутизатор node-gcm - размещен на Heroku, все чаты обращаются к 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;

Метод отправки сообщения

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

0 ответов

Другие вопросы по тегам