Showing fcm notification message in JSON format when app is killed or in background in react-native-fcm - react-native

I am using react-native-fcm library for android device. I am getting notification properly when my application is running, but when my application is in the background or killed then I am getting notification data in JSON format similarly in an image I shared here.
componentDidMount() {
// iOS: show permission prompt for the first call. later just check permission in user settings
// Android: check permission in user settings
FCM.requestPermissions().then(()=>console.log('granted')).catch(()=>console.log('notification permission rejected'));
/*FCM.getFCMToken().then(token => {
console.log('Token',token)
// store fcm token in your server
});*/
this.notificationListener = FCM.on(FCMEvent.Notification, async(notif) => {
console.log('FCM notification', notif)
this.sendRemote(notif)
});
// initial notification contains the notification that launchs the app. If user launchs app by clicking banner, the banner notification info will be here rather than through FCM.on event
// sometimes Android kills activity when app goes to background, and when resume it broadcasts notification before JS is run. You can use FCM.getInitialNotification() to capture those missed events.
// initial notification will be triggered all the time even when open app by icon so send some action identifier when you send notification
/*FCM.getInitialNotification().then(notif => {
console.log('FCM', notif)
this.sendRemote(notif)
//console.log('Initial Notification',notif)
});*/
FCM.getInitialNotification().then((notif: any) => {
// for android/ios app killed state
console.log("ifAny",notif)
if (notif) {
console.log("Any",notif)
// there are two parts of notif. notif.notification contains the notification payload, notif.data contains data payload
}
});
}
sendRemote(notif) {
var data = notif.fcm.body;
var title = notif.fcm.title;
FCM.presentLocalNotification({
title: 'App Name',
body: title,
big_text: title,
large_icon: 'ic_launcher',
priority: 'high',
sound: "default",
click_action: this.clickActions(notif),
show_in_foreground: true,
wake_screen: true,
local: true,
param: notif.notify_about,
paramData: data
});
}
notify_about:'',
fcm:{action:null,
body:"{data:'',time:''}",
color:null,
icon: '',
tag:null,
title:"Notification title"}
this is my data format which I am sending from the server.
Here I want to show only data body. But when the app is killed or in the background, it shows the complete body in the notification.And Its working fine when the app is running.

Related

Duplicate fcm push notification in react native android backgroundhandler

I developed react native application with rnfirebase and notifee for sending the push notification. foreground is working properly, message is displayed only once. but the background notification is displaying twice like one is from messaging().setBackgroundMessageHandler and another one is android's default push notification. First message is from default push notification and next one is from firebase messaging. So how do I remove android's default push notification. I'm also checked that first default notification is not using the firebase messaging and notifee. It's comes from outside of react native like android's native push notification
The notifications that you are seeing are most likely one from firebase and another from Notifee.
In my project I was handling the notifications that were coming from firebase via firebase.messaging().onMessage and inside this listener I was showing a local notification using Notifee so that the notification shows in the foreground.
async showNotificationInForeground(message: FirebaseMessagingTypes.RemoteMessage) {
const { messageId, notification, data } = message
const channelId = await Notifee.createChannel({
id: messageId,
name: 'Pressable Channel',
importance: AndroidImportance.HIGH,
})
await Notifee.displayNotification({
title: notification?.title || '',
body: notification?.body || '',
data,
android: {
channelId,
importance: AndroidImportance.HIGH,
pressAction: {
id: messageId,
},
smallIcon: 'ic_stat_name',
localOnly: true,
},
})
}
However what was happening was that I was calling this showNotificationInForeground method to show the local Notifee notification on both firebase's background and messaging listeners ie: firebase.messaging().onMessage and firebase.messaging().setBackgroundMessageHandler
So what I ended up doing was only calling the showNotificationInForeground method in onMessage listener and not in setBackgroundMessageHandler, which resulted in showing the local notification in the foreground, and the firebase notification in the background.
If this is not the case for you, you are most likely registering an extra notification receiver inside your AndroidManifest.xml file which is causing the duplication
I had the same problem, where there were two notifications a) 1 from notifee (which I wanted to keep) b) from FCM (which I didnt want).
Sending a data only message from my custom server solved the issue. Below is a snippet of the serverside for sending data only message :
const admin = require("firebase-admin");
// Do other stuff like create an express server to listen and trigger sending message
// Note dont forget to to initialize the app
await admin.messaging().sendToDevice(
tokens, // ['token_1', 'token_2', ...]
{
data: {
owner: "Me",
user: "My Friend",
},
},
{
// Required for background/quit data-only messages on iOS
contentAvailable: true,
// Required for background/quit data-only messages on Android
priority: "high",
}
);
You can use other methods as well, just make sure that FCM doesnt include notification and is data only.

React native local notifications

I am new to React Native and need to implement a functionality where the app needs to send the user a notification every day at a certain time. The data to be shown for each day is stored in a json file on the client side and will not change. The notifications are on a schedule. Given that I was hoping there could be a way to just trigger a notification from the app itself.
Does anyone know of a way to achieve this without having to detach the app from expo? I can't use 'react-native-push-notification'without running react-native link and that requires me to detach the app. Is that right?
Is this possible?
Thanks :)
You can do this with expo using the scheduleLocalNotificationAsync function (have a look at these docs for more details). Make sure you have permission to send notifications first. Note that if the notification triggers when the app is in the foreground you won't see a notification but you can still listen to this event.
i. Ask for permission
import { Permissions } from 'expo';
// ... somewhere before scheduling notifications ...
const { status } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
if (status !== 'granted') {
await Permissions.askAsync(Permissions.NOTIFICATIONS);
}
ii. Schedule the notification
import { Notifications } from 'expo';
const notification = {
title: 'Hi there!',
body: 'Tap me to open the app.',
android: { sound: true }, // Make a sound on Android
ios: { sound: true }, // Make a sound on iOS
};
const options = {
time: Date.now() + 10000, // Schedule it in 10 seconds
repeat: 'day', // Repeat it daily
};
// ... somewhere after requesting permission ...
const id = Notifications.scheduleLocalNotificationAsync(notification, options)
// If you want to react even when your app is still in the
// foreground, you can listen to the event like this:
Notifications.addListener(() => {
console.log('triggered!');
});
iii. Cancel the scheduled notification
You can use the returned id of the scheduleLocalNotificationAsync function to cancel the notification.
import { Notifications } from 'expo';
// ... get the id of the scheduled notification ...
Notifications.cancelScheduledNotificationAsync(id)

React Native How to redirect on page when click on notification

I’m using react-native-push-notification on a page with a timer. If the application is in the background after 5 minutes, I’m notified that time has passed. When I click on the notification, it goes to this page. But when I close the application completely and after 5 minutes I click on the notification, it goes to the start page. Now the question is how to make it go to this page?
//
let remainingTime = (this.state.minute * 60 + this.state.seconds) * 1000;
let date = new Date(Date.now() + remainingTime);
PushNotification.localNotificationSchedule({
message: "Message",
date,
soundName: "rush"
});
When any notification is opened or received the callback onNotification is called passing an object with the notification data.
Notification object example:
{
foreground: false, // BOOLEAN: If the notification was received in foreground or not
userInteraction: false, // BOOLEAN: If the notification was opened by the user from the notification area or not
message: 'My Notification Message', // STRING: The notification message
data: {}, // OBJECT: The push data
}
So when onNotification is triggered you can get data object and based on its value you can write your logic of redirection.
To be more clear you can have this code on your start screen or main file
var PushNotification = require('react-native-push-notification');
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
console.log( 'TOKEN:', token );
},
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
// process the notification
}
});

Display custom FCM push notification in React Native iOS

I am working on a react native project which wants to receive the FCM push notification. And I am using the react-native-fcm module. What I want to do is to show the notification manually.
In this module, there is a function
import {Platform} from 'react-native';
import FCM, {FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType} from 'react-native-fcm';
FCM.on(FCMEvent.Notification, async (notif) => {
console.log(notif);
});
where the 'notif' should be the message that was received by the device. However, I cannot receive the console.log(notif); is never called when the notification was sent to the device.
What I want to do is to use the following function to show the notification by handling the notif json manually.
FCM.presentLocalNotification({
id: "UNIQ_ID_STRING", // (optional for instant notification)
title: "My Notification Title", // as FCM payload
body: "My Notification Message", // as FCM payload (required)
sound: "default", // as FCM payload
priority: "high", // as FCM payload
click_action: "ACTION", // as FCM payload
badge: 10, // as FCM payload IOS only, set 0 to clear badges
number: 10, // Android only
ticker: "My Notification Ticker", // Android only
auto_cancel: true, // Android only (default true)
large_icon: "ic_launcher", // Android only
icon: "ic_launcher", // as FCM payload, you can relace this with custom icon you put in mipmap
});
I also realize that the message sent for FCM also would affect how the module to show the message. For more details, check FCM.
I guess my FCM setup should be correct as I can receive the notification. My react-native app can receive the notification if I send the message with key "notification". Like:
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
But the console.log(notif); in the previous function still haven't been called.
I also tried to send the notification with payload
"data" : {
"title" : "Mario",
"body" : "PortugalVSDenmark"
}
But the console.log(notif); is still not been called.
Does anyone know about the mechanism how react-native-fcm and firebase-cloud-messaging work?
Thank you so much!
Please use below code to get FCM token, which should be registered with firebase. After successful registration, You will receive the remote notifications in "notif".
FCM.on(FCMEvent.RefreshToken, (token) => {
console.log("registration token:" + token);
// fcm token may not be available on first load, catch it here
});

React-native FCM: Can't access notification data when the app is in background or killed

Im am trying to make work react-native-fcm, with firebase cloud messaging and a react-native app.
I am focusing mainly in Android
react-native#0.48.0
react-native-fcm#10.0.2
OS: Android - Emulator - 7.0.2
When my app is in foreground, its working perfectly, I receive the data in this function
FCM.on(FCMEvent.Notification, async (notif) => {
And I can handle everything
But when the app is in background, the notification is received, but when I tap the banner, the app goes foreground, the same function is triggered, but the notif object is different, and don't contains my data.
When the app is killed, also the notification is received, but when I tap the banner, the app starts, the
FCM.getInitialNotification()
is triggered, and my notif object doen't also contain the data, the same behaviour than in background
I am testing the format of the messages using node-gcm library, of firebase web interface, but nothing works.
This is a sample of my message, but I have tryed tons of combinations:
let message = new gcm.Message({
priority: 'high',
content_available: true,
timeToLive: 3,
data: {
key1: 'message1',
key2: 'message2'
},
notification: {
title: "Hello, World",
icon: "ic_launcher",
body: "This is a notification that will be displayed if your app is in the background."
},
custom_notification: {
key1: 'message1',
key2: 'message2'
}
});
How should I proceed to send and receive data in those cases? Because is driving me crazy.
If you need more data, ask for it :)
Thanks!!
in my case, i was missing the notification's data setup when building the notification on foreground notification event firebase.notifications().onNotification
new firebase.notifications.Notification()
.setNotificationId(fcmNotification.data.notificacionId)
.setTitle(fcmNotification.title)
.setBody(fcmNotification.body)
.setData(fcmNotification.data) // <- this little bastard
so, when tapping the notification data was undefined on firebase.notifications().onNotificationOpened even when the json that comes in firebase.notifications().onNotification had data field filled