0

我正在使用cordova-plugin-fcm来处理推送通知订阅并监视传入的通知。

当我大约一个月前设置它时,这一切都有效。当应用程序关闭或在后台时,我仍然会收到推送通知。

但如果应用程序在前台,我不会收到任何通知。这实际上很好,因为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);
    }
  });
}]);

房间工厂 - 为推送通知注册聊天者

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

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

0 回答 0