Notification Categories - ionic-framework

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

Related

How to wait for a Flutter app to open before navigating to a particular page by clicking a scheduled notification?

I'm working on a Flutter project where I had to set a scheduled local notification that would fire everyday at 10 am. And, the user should be taken to a certain page of the app upon clicking the notification.
I've completed this part and the functionality works fine when the app is open and the user clicks on the notification.
But the problem arises when the app is closed and the notification is fired and the user clicks on the notification. It doesn't take the user to that certain page. I tried to modify the click handling function by making it an async function. But it doesn't work accordingly.
Can someone suggest me what to do now?
Create a notification handler.
Initialize your notification channel with high importance
Just before your app runs, before runApp(yourApp), create call a foregroundMessageHandler that you have initialized before the void main(){}
the foregroundMessageHandler should be a *TopMost initialization.
in the foregroundMessageHandler function, define the navigation behaviour
I don't know which library you are using for local notifcations. but if you are using flutter_local_notifications library check the link: https://pub.dev/packages/flutter_local_notifications
, you can check the data recived in selectNotification method and redirect the user to required page
void selectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload: $payload');
}
await Navigator.push(
context,
MaterialPageRoute<void>(builder: (context) => SecondScreen(payload)),
);
}
other libraries should have same functionality.

Flutter push notifications app background : firebase_messaging

I want to display a push notification when my app is in the background.
I am using the flutter_local_notifications package and the firebase_messaging package.
Push notifications are working great with firebase_messaging and when my app is the background.
However, the below method :
// The following handler is called, when App is in the background.
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
is not called if a RemoteNotification object is passed through the RemoteMessage :
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print('message from background handler');
print("Handling a background message: ${message.messageId}");
// If this is null, then this handler method is called
RemoteNotification remoteNotification = message.notification;
showNotificationFromData(message.data);
}
Therefore, i have to pass the message.data object which is a Map<String, dynamic>.
My problem is that i don't receive push notification anymore when this firebaseMessagingBackgroundHandler handler method is called.
So i have been trying to use the flutter_local_notification package to display a push notification but as it is said, it's "local" so it's working fine in the Foreground but apparently not in the background (the same code, with the same data is not showing in the background as a push notification).
Question :
I need to call the firebaseMessagingBackgroundHandler handler to handle events in my app. So i can do to still have push notifications when my app is in the background please ?
Thanks
Okay i have found the solution. It was to set the content_available value to True in the server-side code.
To replace the firebase_messaging.Notification item, we need to override to the android and apns configs.
This looks like this in python :
apnsConfig = messaging.APNSConfig(
payload=messaging.APNSPayload(
aps=messaging.Aps(
content_available=True,
)
),
)
I am now receiving push notifications and call the background handler inside the dart code.
I know this bit too late but anyone trying to get custom notification using firebase then here is the solution
For Android (Flutter)
On Android, notification messages are sent to Notification Channels which are used to control how a notification is delivered. The default FCM channel used is hidden from users, however provides a "default" importance level. Heads up notifications require a "max" importance level.
This means that we need to first create a new channel with a maximum importance level & then assign incoming FCM notifications to this channel. we can take advantage of the flutter_local_notifications package
Add the flutter_local_notifications package to your local project.
Create a new AndroidNotificationChannel instance:
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.max,
);
(keep in mind this is example code but you can custimize notification through notification channel code)
Create the channel on the device:
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
Once created, we can now update FCM to use our own channel rather
than the default FCM one. To do this, open the
android/app/src/main/AndroidManifest.xml file for your
FlutterProject project. Add the following meta-data schema within
the application component:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="high_importance_channel" />
now whenever you send notification specify your channel id and your app automatically show your custom notification (through api or firebase console)
{
"message":{
"token":"token_1",
"android_channel_id":"high_importance_channel" //specify channel id here
"data":{},
"notification":{
"title":"FCM Message",
"body":"This is an FCM notification message!",
}
}
}
as for ios they don't support notification channel i don't have necessary resources and info how things works if you guys know comment below will be much appriciated

Is there way to use push notifications in our ionic 4 project?

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

How to control when to ask for notification permission with FCM plugin

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!

Cancel sent Web Push notifications

I'm sending push notifications to my website users when they (for example) receive a private message.
That notification goes to all browsers subscribed for that user. So could be desktop, mobile, work computer etc.
What I would like to do is close all the sent notifications once the user has a read a message.
So user logs in on mobile, reads the private message - at this point I want all the previously sent notifications for that PM to be closed/cancelled.
Is this possible?
Thanks in advance!
Matt
Yes this is possible, but not silently. For example, Chrome will replace the notification with a new one saying "This site has been updated in the background".
There are two separate APIs: the Push API which "gives web applications the ability to receive messages pushed to them from a server", and the Notification API which "is used to configure and display desktop notifications to the user".
The Notification API provides Notification.close(), which cancels the display of a notification.
You can use the Push API to trigger Notification.close(). Here's a sample which should go in your service worker:
self.addEventListener('push', async event => {
const data = event.data.json();
if (data.type === 'display_notification') {
self.registration.showNotification(data.title, data.options);
} else if (data.type === 'cancel_notification') {
const notifications = await self.registration.getNotifications({
tag: data.notificationTag
});
for (notification of notifications) {
notification.close();
}
} else {
console.warn("Unknown message type", event, data);
}
});
However! This design means that your cancel_notification message won't display a notification. This violates some browser policies, for example Chrome will display a new notification saying "This site has been updated in the background".