Can I get push notifications with React Native when app is closed? - react-native

I'm trying to get notifications and update launcher icon badge on IOS with React-Native/RNFirebase when app is closed. But unfortunately it seems RNFirebase doesn't have any support for it. onNotification() listener doesn't seem working when app is closed. (background modes/push notifications are enabled on XCode)
Is there any workaround for that to update launcher icon badge when notification received and app is closed?

If your app is closed, you can check if it was opened by a notification using:
firebase.notifications().getInitialNotification()
here is a sample using it:
const notificationOpen = await firebase
.notifications()
.getInitialNotification();
if (notificationOpen && notificationOpen.notification) {
let { title, body, data } = notificationOpen.notification;
if (!title && !body) {
title = data.title;
body = data.body;
}
const notification: Notification = notificationOpen.notification;
//firebase.notifications().removeDeliveredNotification(notification.notificationId);
this.handleNotificationActions(
title,
body,
data,
navigator,
t,
"background"
);
}

Related

Open deep link url when clicking on FCB notification for both iOS and Android

I have a react-native app using react-native-firebase-messaging to send push notifications to android and iOS devices. I'm trying to embed a deep link in the FCM message so that users clicking on the notification will be routed to a specific section of the app. I've seen this SO post which shows how the link property can be added but it's specific to android. How can I add a deep link url to notifications sent to both iOS and Android devices?
Without having deep link you can use notification click handler of react-native-firebase-messaging and pass the data in the notification payload which screen you want to navigate.
Check this link for documentation and make sure you have register background handler in index.js as shown here
useEffect(() => {
// Assume a message-notification contains a "type" property in the data payload of the screen to open
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
navigation.navigate(remoteMessage.data.type);
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
setInitialRoute(remoteMessage.data.type); // e.g. "Settings"
}
setLoading(false);
});
}, []);

React native firebase notification shows while the app is running

I've made an app using react native firebase 5.6.0. I'm getting notifications from firebase and displaying them with this piece of code:
this.notificationListener = firebase
.notifications()
.onNotification((notification: Notification) => {
notification.android
.setChannelId('channel')
.android.setSmallIcon('ic_launcher')
.android.setPriority(firebase.notifications.Android.Priority.Max)
.android.setColor('#121243');
firebase.notifications().displayNotification(notification);
});
The problem is push notifications showing even when the app is on foreground and running. I want them to only show when the app is on background.
I've solved the problem using AppState
this.notificationListener = firebase
.notifications()
.onNotification((notification: Notification) => {
if (AppState.currentState != 'active') {
notification.android
.setChannelId('channel')
.android.setSmallIcon('ic_launcher')
.android.setPriority(firebase.notifications.Android.Priority.Max)
.android.setColor('#121243');
firebase.notifications().displayNotification(notification);
}
});
So if the app is in active state the notification won't show.

Launch React Native App from Background on Notification Received

I am working on react native application and my requirement is to launch specific screen on Notification received.
Notification is working fine in all state i.e. Foreground or background.
I am using below library:
react-navigation
#react-native-firebase/messaging
react-native-push-notification
Below is the code for handling notification :
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
let text = {
title: remoteMessage.data.title,
body: remoteMessage.data.body,
}
notif.cancelAll();
notif.localNotif(text);
NavigationService.navigate('Contact', { userName: 'Lucy' })
});
Also wrote a navigation code on notification received method referring
https://reactnavigation.org/docs/4.x/navigating-without-navigation-prop
I can see app navigate to particular screen but its not launching app.
Can anyone help me with this?

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)

FCM Push notification with user's avatar

I'm trying to create a push notification like whatsApp or Gmail where the user avatar's is present in the notification. Is there a way to do it in react-native, especially using expo?
this is my payload for fcm
{
"GCM": "{ \"notification\": { \"title\": \"Sender1\" }, \"text\": \"test message\" } }"
}
This is an example which I got from Google which I'd like to achieve.
Answer (Source): How to set the app icon as the notification icon in the notification drawer
by user #manikanta
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
android.app.NotificationManager notificationManager =
(android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
Set Large icon does the trick.Comment below if you have any further info
If you're using React Native (react-native-firebase):
const notif = new firebase.notifications.Notification({
show_in_foreground: true,
})
.android.setSmallIcon('#mipmap/ic_notification') // app icon
// source image might be:
// URL
// android resource e.g. #mipmap/ic_launcher
let source_image = "";
notif.android.setLargeIcon(source_image) // user avatar
Source: https://rnfirebase.io/docs/v5.x.x/notifications/reference/AndroidNotification#setLargeIcon