We currently have an Ionic and Firebase project that we coded. In this project, we want to use push notifications. But our trouble is:
We are looking for a push notification plugin, like WhatsApp application. For example, when we send a message to a person, we want the notification to go to the person we're texting from, not everyone. But we couldn't find a free way to do that. Do you have any suggestions? Thank you.
Firebase Cloud Messaging By using cordova-plugin and ionic-native:Ref. Url
import { FCM } from '#ionic-native/fcm/ngx';
constructor(private fcm: FCM) {}
this.fcm.getToken().then(token => {
//you can store device token in firebase, later you can target push notification from firebase console this token id
backend.registerToken(token);
});
this.fcm.onNotification().subscribe(data => {
if(data.wasTapped){ / * true , means the user tapped the notification from the notification tray and that’s how he opened the app. */
console.log("Received in background");
} else {// false , means that the app was in the foreground (meaning the user was inside the app at that moment)
console.log("Received in foreground");
};
});
this.fcm.onTokenRefresh().subscribe(token => {
//update device token
backend.registerToken(token);
});
I don't recommend you to use FCM plugin. It has no methods to manage your notifications in your app (clear all or clear some special notification.
It is better to use phonegap-push-plugin or One Signal
Related
In an Ionic 3 app, I am using the Cordova FCM plugin for notifications. I would like to ask for notification permission when my users click a button within the app.
But, now the app asks for notification on launch. I’d rather ask for notifications later. Not right away. I tested this on iOS devices only so far.
I am using the FCM plugin only in app.component.ts. FCM plugin code should run on the condition that a database variable exists and equals to a certain value. This value is changed in the app when the user clicks a button. I was hoping the the plugin would kick in when the button is clicked but not when the app starts. Here is my code. Please help!
app.component.ts
platform.ready().then(() => {
//START: notification operator
const authListener=afAuth.authState.subscribe(user => {
if (user) {
this.userId = user.uid;
//check if user answered yes to the question asked after first clicking a follow button
firebase.database().ref(`/members/${this.userId}/notStats/`).on("value", res => {
if (res.exists()) {
if (res.val().notifAllowed == true ) {
//START: get device token and save in user members
fcm.getToken().then(token => {
afDatabase.object(`/members/${this.userId}/notificationStatus/`).update({deviceToken: token});
});
//START: subscribe to notification listener
fcm.onNotification().subscribe(data => {
if (data.wasTapped) {//Notification tapped by the user
console.log(JSON.stringify(data));
} else { //App was in foreground when notification was sent
console.log(JSON.stringify(data));}
});
} //end: if notifsAllowed saved in database as true
} //end: if exists
});//end: firebase listener
authListener.unsubscribe();} else {authListener.unsubscribe();}});
//notification operator: END
});
How can I ask for notification permission when the button in the app is first clicked? I do not wish the app to ask for permission to send notifications on first launch. It makes for terrible user experience, asking for permission at the beginning before users even get to see the app.
Thanks!
I have created one of the mobile application using ionic 1 and firebase. Now I want to create a notification categories like channel where user can select which notification they needed.
Here I have shared the code for push notification which i have used and this code is working , i want to create the notification categories, the above code is working for push notification for my mobile application.
Now I need a help that how can I create the channel notification categories in my mobile application
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) );
}
});
I have been trying for several months to implement an app that receives notifications whose content I want to be stored in the database of my application. I am using the Firebase Messagging plugin and I am receiving the notifications correctly, both in Foreground and in Background.
However, in the background I am unable to execute my callback without the need to press the notification explicitly by the user. Likewise, there is no way to increase the badge of the application when it is not open.
Now, I do not understand how applications like WhatsApp, Telegram and any other application that is not made by mere mortals work. How is it possible that they can get the data in backgroud, manage the badges, synchronize messages, etc? Being that, supposedly the services like Firebase are limited in background. Even with plugins like Background Mode my application is suspended by Android when the user closes it.
The code that I am currently using to handle notifications is the following:
// In foreground (WORKS)
this.firebaseMessaging.onMessage().subscribe((notificacion) => {
// Insert in DB
...
});
// In background (DOESN'T WORK)
this.firebaseMessaging.onBackgroundMessage().subscribe((notificacion) => {
// Insert in DB
...
});
What alternative is left? The only thing that occurs to me is to use notifications in Foreground and background only as a warning. So every time I open the application I'll have to call a message synchronization callback with the server (with badge management included).
If someone has some better way, I would greatly appreciate it if you throw a little light on the subject.
From already thank you very much
Ok, after more than a year I think it's time to close this question. I solved the problem this way:
Suppose I need to get a list of messages. This action is made by a function called getMessages()
When a new message is created in the backend, I send a push notification through Firebase service.
If the push notification is received in foreground I refresh call the method directly:
this.firebaseMessaging.onMessage().subscribe((notificacion) => {
getMessages();
});
If the push notification is received in background and the user taps on it there isn't a problem as it's supported by the plugin:
this.firebaseMessaging.onBackgroundMessage().subscribe((notificacion) => {
getMessages();
});
If the push notification is received in background but the user DOES NOT tap on it and opens the app in another way than the notification, we need to excecute the corresponing function when the app is opened in app.component.ts file:
this.platform.ready().then(() => {
getMessages();
// Extra stuff like this.statusBar.styleDefault(); or this.splashScreen.hide();
});
That way all the cases are considered! You should keep in mind that apps like Whatsapp or Telegram are developed in official technologies like Java or Kotlin which not only have official native plugins, also its code are excecuted natively and not in a limited browser as Cordova or Capacitor frameworks do
I want to use notification with my app. I have checked ionic native and find some information.
First;
Local Notification
Second;
Push
What do I want to do? I am using MySQL Database and I have two tables users and points. When I add points for one user, I want to send notification for only this user. How can I do this? Which can I use service?
As per your required I suggest you to use Push Notifications using FCM.
push notifications help to send notification into two or more ionic apps.
please follow these steps.
go to 'http://console.firebase.google.com' and create an android app make sure that app package name also mention in config.xml file.
Install the Cordova and Ionic Native plugins in App:
ionic cordova plugin add cordova-plugin-fcm
npm install --save #ionic-native/fcm
use this code in your 'app.component.ts' file with in initializeApp
/getToken generates a device token that helps you to send notification on this device.you have to store this token in your database when app is open./
fcm.getToken().then(token=>{
console.log(token);
});
fcm.onNotification().subscribe(data=>{
if(data.wasTapped){
console.log("Received in background");
} else {
console.log("Received in foreground");
};
});
fcm.onTokenRefresh().subscribe(token=>{
console.log(token);
});
Now the real process that you have to follow for send notification
/here is you have to add device token that is you have store in your database and your firebase api key./
let body = {
"notification":{
"title":"New Notification has arrived",
"body":"Notification Body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
"data":{
"param1":"value1",
"param2":"value2"
},
"to":"Device token/ID",
"priority":"high",
"restricted_package_name":""
}
let options = new HttpHeaders().set('Content-Type','application/json');
this.http.post("https://fcm.googleapis.com/fcm/send",body,{
headers: options.set('Authorization', 'key=YourAuthToken'),
}).subscribe();
hope this is helpful for you.
Thank You.
Push notification works the same way as local notification with a minor difference. Push notifications require connectivity and a server infrastructure of some kind to send the notification. With local notification you can trigger the notification with conditions. You will get the notification even if the app is closed and you’re offline. And having both notifications won’t cause implications.
In your case, you should go with Push Notification.If in future if you want to change the parameter to send notification it will be easy for you to maintain.No need to update the app
You can use FCM- Firebase Cloud Messaging on server side and in client side you can use PhoneGap push plugins to generate device token
here are the plugins
<plugin name="phonegap-plugin-push" source="npm" spec="1.8.4">
<variable name="SENDER_ID" value="XXXXXXX" />
</plugin>
I have an inherited Ionic framework app that is using Ionic.io
The app authorises against our API, and is given an API token to use in future requests.
I'm trying to work on push notifications - I've set up ionic push, and can trigger push notifications out to all users with no problems.
I'd like the ability to target specific users / devices to send notifications, and I understand that to do this, I have to register the device to generate a token.
Within my $ionicPlatform.ready function, I have:
$ionicPush.register().then(function(t) {
return $ionicPush.saveToken(t);
}).then(function(t) {
console.log('Token saved:', t.token);
});
This however does not seem to be returning a token, and calling
console.log($ionicPush);
Shows that the token is not set.
Any ideas here? What am I missing?
So after digging though some documentation, I found that the issue was linked with the ionic user.
In the main run function, I fire off a
if ($ionicAuth.isAuthenticated()) {
If this fails, I try a login of a user, and a register of the user if appropriate. (user is already logged in using a custom auth token against our api)
Before I attempt to register the token, I then have to reload the user in order to have the app save off and push back up to ionic.io.
$ionicUser.load().then(function() {
$ionicPush.register().then(function(t) {
console.log('Token sent:', t.token);
return $ionicPush.saveToken(t);
}).then(function(t) {
console.log('Token saved:', t.token);
});
});