Custom click on Ionic notification using Firebase - firebase

I have been using ionic and FCM (Firebase Cloud Messaging) for notification.
I get the notification on my app and now I have 2 issues. First, if its a normal notification like not with advanced options in Firebase Console > Notification, then it doesn't play any sound, but when it's data Notification, then it does play a sound. Second, I want to open a particular page of my app on notification click.
So how do I do that?
Note: I am using ionic not an ionic2.

First issue:
We have sound in both situations. Have you tried to send an empty data object?
Second issue:
Just assuming you use the Cordova FCM plugin. Otherwise install it with
cordova plugin add cordova-plugin-fcm --save
Use the data with an ID to the right datapage and then do something like:
angular.module('app', ['ionic'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova) {
FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
$state.go('yourpage', {id:data.pageId});
console.log('onNotification tapped true');
} else {
//Notification was received in foreground. User needs to be notified.
console.log('onNotification tapped false');
}
},
function(msg){
console.log('onNotification callback successfully registered: ' + msg);
},
function(err){
console.log('Error registering onNotification callback: ' + err);
}
);
}
});
});

Related

PWA listen for event upon receiving push notification (while app is not running)

I'm trying to get the data that i receive from my push notification and display it in the pwa. The idea is that i have a push notification coming in with a text body, then the user clicks on the push notification and the PWA opens up with the data from the push notification displayed on the section. I have managed to get it work when it is open as i placed it in the mounted lifecycle and the function activates when it listens to the message that comes in. The only problem is when the push notification comes in, the user will not be having the PWA all the way. So how do i overcome this? I have tried inserting in other lifecycle methods but it seems redundant since the PWA is not even opened yet when the push notification arrives. Hope anyone here can advise on this. Thank you very much.
mounted(){
navigator.serviceWorker.addEventListener('message', (e) => {
console.log('Push Notification received');
console.log(e.data.firebaseMessagingData.notification.body);
var timestamp = new Date().toLocaleTimeString(undefined, {hour: '2-digit', minute: '2-digit'});
const robotMessage = {
text: e.data.firebaseMessagingData.notification.body,
isRobot: true,
timestamp: timestamp
}
firebase
.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.collection("messages")
.add({
robotMessage: robotMessage.text,
timestamp: robotMessage.timestamp
});
this.messages.push(robotMessage);
});
}

How can I access title and body data from pushNotificationActionPerformed into the ionic application with capacitor

I'm using Capacitor Push Notifications into my app. I've follow the capacitor tutorial from capacitor website, and implemented this code:
onPushNotifications() {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
// On succcess, we should be able to receive notifications
PushNotifications.addListener('registration', (token: PushNotificationToken) => {
console.log('Push registration success, token: ' + token.value);
});
// Some issue with our setup and push will not work
PushNotifications.addListener('registrationError', (error: any) => {
console.log('Error on registration: ' + JSON.stringify(error));
this.showToast('Erro ao ativar as notificações push.');
});
// Show us the notification payload if the app is open on our device
PushNotifications.addListener('pushNotificationReceived', (notification: PushNotification) => {
this.showToast(notification.title + '\n' + notification.body);
this.addNewNotification(notification);
});
// Method called when tapping on a notification
PushNotifications.addListener('pushNotificationActionPerformed', (notification: PushNotificationActionPerformed) => {
this.addNewNotification(notification.notification.data);
});
}
With this, I could access data title and body from push notification when the app is running in foreground (using pushNotificationReceived). But when the app is running in background I could access the title and body to save in an array, for exemple.
I tried implement this code:
// Method called when tapping on a notification
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: PushNotificationActionPerformed) => {
let notif = this.state.notifications;
notif.push({ id: notification.notification.data.id, title: notification.notification.data.title, body: notification.notification.data.body })
this.setState({
notifications: notif
})
}
);
From this website https://medium.com/enappd/firebase-push-notification-in-ionic-react-app-using-capacitor-b6726c71bda4
But I got no functional answer. I keep getting undefined in title and body.
Please, can someone help me?
Thanks!
Your payload should contain:
notification_foreground,
notification_title,
notification_body.
You have to make:
notification_foreground = true
Sadly that’s how push with notification payload work, when in background or closed the OS handles them, using the title and body to display the notification in the tray, but when you tap them, that information is no longer available for the app.
Use data payload to pass any data you want.

React Native: managing notification on RNFirebase

I have successfully implemented a basic notification feature using react-native-firebase library, everything is working as expected, information is properly received and ready to be used for a purpose I have yet to determine. My code currently look like this for the notification handling part:
componentDidMount() {
/**
* When app on foreground, rewrap received notification and re-send it as notification using channelId
* A workaround because channelId never set by default by FCM API so we need to rewrap to make sure it is
* shown on user's notification tray
*/
this.notificationListener = firebase.notifications().onNotification((notification) => {
//data object must have channelId props as a workaround for foreground notification on Android
console.log('Notif ', notification);
notification.android.setChannelId(notification.data.channelId);
firebase.notifications().displayNotification(notification);
});
//On Notification tapped, be it from foreground or background
this.notificationOpen = firebase.notifications().onNotificationOpened((notificationOpen) => {
//body and title lost if accessed from background, taking info from data object by default
const notification = notificationOpen.notification;
console.log('Open ', notification)
Alert.alert(notification.data.title, notification.data.body);
});
//When notification received when app is closed
this.initialNotification = firebase.notifications().getInitialNotification()
.then((notificationOpen) => {
//body and title lost if accessed this way, taking info from data object where info will persist
if (notificationOpen) {
const notification = notificationOpen.notification;
console.log('Initial ', notification)
Alert.alert(notification.data.title, notification.data.body);
}
});
}
componentWillUnmount() {
this.notificationListener();
this.initialNotification()
this.notificationOpen();
}
The above code let me use any information I sent from firebase console or a php server set up by my colleague from within the above scope (not sure how the server side implementation was done, but it gives me the exact same notification object on my end).
So that's good and all, but the problem is when I set badge on IOS from firebase console, the badge doesn't go away once I opened the notification.
I have been trying to figure out if there's any extra bit I have to add to the above block to programatically decrement the badge counter, but have no luck so far.
So if anyone here can show me how to manage these notification objects properly (especially explaining the nature and lifecycle of these objects -- i.e. which data on which property/method persists or is static within the scope of the notification object) on both Android and IOS, that would be greatly appreciated :)
Turns out a simple firebase.notifications().setBadge(0) on root componentDidMount() clears out the badge count whenever the app is opened.
May need to use firebase.notifications().removeAllDeliveredNotifications() or firebase.notifications().cancelAllNotifications() to remove them from notification tray too.
May be you have to set code for badge while creating a notification
this.notificationListener = firebase.notifications().onNotification((notification) => {
const localNotification = new firebase.notifications.Notification()
.setNotificationId(notification.notificationId)
.setTitle(notification.title)
.setSubtitle(notification.subtitle)
.setBody(notification.body)
.setData(notification.data)
.ios.setBadge(notification.ios.badge);
firebase.notifications()
.displayNotification(localNotification)
.catch(err => console.error(err));
}
Put this line in code .ios.setBadge(notification.ios.badge); while building a notification and try again

User based notifications with the Bluemix Push Notification service

Currently developing a Cordova app and wanted to use the IBM Bluemix Push Notification service to send user based push notifications.
According to the documentation here, seems like the first step is to call MFPPush.initialize(appGuid, clientSecret), which I tried to do. But this function is not present in the plugin interface and therefore I get an 'undefined' error when running the app.
Moreover, the doc also talks about calling MFPPush.registerDevice({},success,failure,userId). However, when I look at the plugin javascript interface, it only takes 3 parameters.
Could someone please give some advice to help me sort this out?
Thanks.
I just ran the Bluemix Cordova hellopush sample which should help you out. Make sure you follow the directions in the README, and make sure to change the route and guid in your index.js (it should look something like this):
route: "http://imfpush.ng.bluemix.net",
guid: "djkslk3j2-4974-4324-8e82-421c02ce847c",
You will be able to find the route and guid in your Push Notifications service credentials.
After running it by following the directions (and ensuring that you have GCM / APNS set up correctly for whatever platform you are using), you should be greeted with this screen after clicking register:
#johan #joe Cordova app can use the IBM Bluemix Push Notification service to send user based push notifications. Please follow the below example using BMSPush to register for Push Notifications.
// initialize BMSCore SDK
BMSClient.initialize("Your Push service region");
// initialize BMSPush SDK
var appGUID = "Your Push service appGUID";
var clientSecret = "Your Push service clientSecret";
// Initialize for normal push notifications
var options = {}
BMSPush.initialize(appGUID,clientSecret,options);
// Initialize for iOS actionable push notifications and custom deviceId
var options ={"categories":{
"Category_Name1":[
{
"IdentifierName":"IdentifierName_1",
"actionName":"actionName_1",
"IconName":"IconName_1"
},
{
"IdentifierName":"IdentifierName_2",
"actionName":"actionName_2",
"IconName":"IconName_2"
}
]},
"deviceId":"mydeviceId"
};
BMSPush.initialize(appGUID, clientSecret, options);
var success = function(response) { console.log("Success: " + response); };
var failure = function(response) { console.log("Error: " + response); };
// Register device for push notification without UserId
BMSPush.registerDevice(options, success, failure);
// Register device for push notification with UserId
var options = {"userId": "Your User Id value"};
BMSPush.registerDevice(options, success, failure);
Please go through the Bluemix Cordova Plugin Push SDK doc link.

push not initilizing when trying to create hybrid android application

I am trying to implement push notifications using bluemix and mobilefirst. I have used the following links to implement
http://www.ibm.com/developerworks/library/mo-cordova-push-app/
http://mbaas-gettingstarted.ng.bluemix.net/hybrid#initialize-push -
When i run the the below code I am getting the following message in the console:
initPush called----------------
main.js:29 calling bluemix initialize with values----------------------
IBMBluemixHybrid.js:2956 [INFO] [DEFAULT] Hybrid initialize ["applicationid","applicationsecret","applicationroute"]
I neither see the device details reflected in the bluemix registered list. Can you please help me on this ?
var values = {
applicationId:"applicationId",
applicationRoute:"applicationRoute",
applicationSecret:"applicationSecret"
};
console.log("initPush called---------------------------------");
console.log("calling bluemix initialize with values--------------------------------");
IBMBluemix.initialize(values).then(function(status) {
console.log("IBM Bluemix Initialized", status);
return IBMPush.initializeService();
}, function (err) {
console.error("IBM Bluemix initialized failed" , err);
}).then(function(pushObj) {
function pushReceived(info) {
console.log("registerListener - " + info.alert);
alert('got a push message! ' + info.alert);
}
console.log("IBM Push Initialized", pushObj);
push = pushObj;
return push.registerDevice("LisaTest","Lisa123","pushReceived");
}, function (err) {
console.error("IBM Bluemix Push initialized failed" , err);
});
You need to replace "applicationId", "applicationRoute", and "applicationSecret" in the code
var values = {
applicationId:"applicationId",
applicationRoute:"applicationRoute",
applicationSecret:"applicationSecret"
};
with those obtained from your Bluemix backend application.
From the bluemix dashboard for your application click mobile options in the top right to see your ID and Route.
For the secret navigate to the Mobile Application Security dashboard from the link on the right, and your secret will be displayed on that page.

Resources