FCM data not received when app is killed - ionic-framework

I'm receiving notifications sent by FCM console even if the app is killed.
Here's my client code:
$ionicPlatform.ready(function() {
FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
alert( JSON.stringify(data) );
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
alert( JSON.stringify(data) );
}
},
function(msg){
console.log('onNotification callback successfully registered: ' + msg);
},
function(err){
console.log('Error registering onNotification callback: ' + err);
}
);
})
The problem is the notification call back is not received. The log data is showing:
View not ready. SAVED NOTIFICATION: javascript:FCMPlugin.onNotificationReceived()

try to put FCMPlugin in
// Ionic Starter App
angular.module('starter', ['ionic', 'starter.controllers', 'ngCordovaOauth'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
try{
FCMPlugin.onNotification(
function(data){
console.log('DATA ==>: '+data);
if(data.wasTapped){
//Notification was received on device tray and tapped by the user. 
console.log('01');
console.log( JSON.stringify(data) );
}else{
//Notification was received in foreground. Maybe the user needs to be notified. 
console.log('02');
//alert( JSON.stringify(data));
}
},
function(msg){
console.log('onNotification callback successfully registered: ' + msg);
},
function(err){
console.log('Error registering onNotification callback: ' + err);
}
);
}catch(e)
{
console.log('in login'+e)
}
});
})

Related

FCM using push notification ionic 4

FCM using push notification ionic 4
i had attach my error log too,
i installed https://ionicframework.com/docs/native/fcm
i am using ionic cli---4.12.0
I am trying to send push notification on my device with the help of FCM
and ionic 4. But I'm unable to get token,. I'm getting device token for iOS
and I've import app.module.ts,app.component.ts aslo ,
i have try to store token in local storage but im getting null value
is there i missing??
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleLightContent();
this.splashScreen.hide();
this.fcm.subscribeToTopic('marketing');
//Receving
this.fcm.getToken().then((token) => {
localStorage.setItem('token', token);
}, (err) => {
alert(JSON.stringify(err));
});
this.fcm.onNotification().subscribe((data) => {
console.log("Data :", data);
if (data.wasTapped) {
console.log("Received in background " + JSON.stringify(data));
alert("Received in background " + JSON.stringify(data));
} else {
console.log("Received in foreground" + JSON.stringify(data));
alert("Received in foreground" + JSON.stringify(data));
}
});
//Updating
this.fcm.onTokenRefresh().subscribe((token) => {
localStorage.setItem('token', token);
console.log(token);
alert('refresh token: ' + token);
});
this.fcm.unsubscribeFromTopic('marketing');
});
}

$cordovaPushV5 onNotification not firing

I am trying to implement push notifications in Ionic V1 using $cordovaPushV5 but I am not able to get to work. I am able to get the device registration ID but when I test notifications using Firebase Cloud Messaging, it doesnt work. Below is app.js code -
// ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
var app = angular.module('starter', ['ionic', 'ngCordova'])
.run(function ($ionicPlatform, $cordovaPushV5, $rootScope, $cordovaLocalNotification) {
$ionicPlatform.ready(function () {
// hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (cordova.platformId === 'ios' && window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
window.StatusBar.styleLightContent();
}
console.log('app.js');
var options = {
android: {
senderID: "981686413111"
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
};
$cordovaPushV5.initialize(options).then(function (result) {
// start listening for new notifications
$cordovaPushV5.onNotification();
// start listening for errors
$cordovaPushV5.onError();
// register to get registrationId
$cordovaPushV5.register().then(function (registrationId) {
// save `registrationId` somewhere;
console.log(registrationId);
localStorage.setItem('deviceID', registrationId);
}, function (err) {
console.log(err);
});
});
$rootScope.$on('$cordovaPushV5:notificationReceived', function (event, data) {
console.log(data);
});
$rootScope.$on('$cordovaPushV5:errorOccurred', function (event, error) {
console.log("notification error occured");
console.log("event object: ", event);
console.log("error object: ", error);
});
$cordovaPushV5.finish().then(function (result) {
// OK finished - works only with the dev-next version of pushV5.js in ngCordova as of February 8, 2016
}, function (err) {
// handle error
console.log('finish error');
});
//$cordovaPushV5.unregister();
});
});
//# sourceMappingURL=app.js.map
Here is my screenshot of FCM history -
FCM History
I follow the following links to implement -
https://github.com/yafraorg/yafra/wiki/Blog-Ionic-PushV5
What am I missing ?

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

Ionic PushNotification

I have implemented ionic push notification on my app for android. Push notification works well when app is not running(either is in background or not started), however, it does not get status bar notification(notification bar) or vibration that worked when running in background or not started at all.
$ionicPlatform.ready(function() {
localStorage.myPush = ''; // I use a localStorage variable to persist the token
var tokenID = '';
$cordovaPushV5.initialize( // important to initialize with the multidevice structure !!
{
android: {
senderID: "457390407561"
},
ios: {
alert: 'true',
badge: true,
sound: 'false',
clearBadge: true
},
windows: {}
}
).then(function (result) {
$cordovaPushV5.onNotification();
$cordovaPushV5.onError();
$cordovaPushV5.register().then(function (resultreg) {
localStorage.myPush = resultreg;
console.log(localStorage);
}, function (err) {
// handle error
});
});
$rootScope.$on('$cordovaPushV5:notificationReceived', function(event, data){
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
console.log("notification received");
console.log(event);
console.log(data);
console.log(data.message);
console.log(data.title);
console.log(data.count);
console.log(data.sound);
if (data.additionalData.foreground === true) {
// do something if the app is in foreground while receiving to push - handle in app push handling
console.log("notification received in foreground");
}
else {
// handle push messages while app is in background or not started
console.log("notification received in background");
$state.go('app.orderlist');
}
});
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
Any advice or suggestion?
Thank you in advance.
You can add
forceShow: true
like below
$cordovaPushV5.initialize( // important to initialize with the multidevice structure !!
{
android: {
senderID: "xxxxxxxxx",
forceShow: true
},
ios: {
alert: 'true',
badge: true,
sound: 'false',
clearBadge: true,
},
windows: {}
}
)

Facebook phonegap login

I am trying to log in with Facebook using PhoneGap. It seems to works well.
But on iOS 6.0, the login failed with the message "The operation couldn't be completed.(com.facebook.sdk error 5)".
If I don't set the account in setting of my iPhone, the plugin logged in using browser.
There is no problem.
But if I set the account in the setting, it shows upon message.
If I close the app, and launch again, it logs in successfully.
This function checks whether logged in already.
function getLoginStatus() {
FB.getLoginStatus(function(session) {
console.log('Got the user\'s session(facebook): ', session);
if (session.status == 'connected') {
FB.api('/me', {
fields: 'id, name, email'
},
function(response) {
if (response.error) {
console.log('get user name failed');
login(); // login to Facebook.
}
else
{
console.log('FB name, ' + response.name);
console.log('FB id, ' + response.id);
console.log('FB email, ' + response.email);
siteLogin(response); // login to my site.
}
});
} else {
console.log('get user name failed 2');
login(); // login to Facebook
}
});
}
Facebook login function
function login() {
FB.login(
function(response) {
if (response.session) {
alert('logged in');
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
}
This is the event function.
FB.Event.subscribe('auth.login', function(response) {
FB.api('/me',{ fields: 'id, name, email' }, function(response1) {
if (response1.name !== undefined)
{
siteLogin(response1); // login to my site.
}
else
{
// I think here I get the message "The operation couldn't be completed.(com.facebook.sdk error 5)"
alert('error.');
}
});
});