Hello folks. I hope you all are doing well.
In this tutorial, you're going to learn how to handle and schedule local push notification with firebase using react native development.
There are two types of notifications, remote and local notifications.
Remote Notifications
With remote notifications, we should use one of our company servers to push data to user devices via any notification service.
Local Notifications
In local notification, notification is scheduled and triggered by an app on a particular time and date and delivered on the same device.
In this tutorial, we will use local notification to schedule reminder.
Prerequisites
This tutorial requires basic knowledge of React Native development. To set up your development machine, follow the official guide here.
We are going to use react-native-firebase to handle push notification
Before implementing to schedule push notification, please visit this article to configure project.
After the configured project, Let's create one FCMService to handle notification
Create one folder in project directory named it as src
and under the src
folder create one file name as FCMService.js
Before use push notification in the app, we require the user permission to display notifications in the app. If the user denies permission it explicitly changes from the settings.
First, let's write below code in FCMService.js to get permission from the user
checkPermission = (onRegister) => {
firebase.messaging().hasPermission()
.then(enabled => {
if (enabled) {
//user has permission
this.getToken(onRegister)
} else {
//user don't have permission
this.requestPermission(onRegister)
}
}).catch(error => {
console.log("Permission rejected", error)
})
}
getToken = (onRegister) => {
firebase.messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
onRegister(fcmToken)
} else {
console.log("User does not have a device token")
}
}).catch(error => {
console.log("getToken rejected ", error)
})
}
requestPermission = (onRegister) => {
firebase.messaging().requestPermission()
.then(() => {
this.getToken(onRegister)
}).catch(error => {
console.log("Requested persmission rejected ", error)
})
}
deletedToken = () => {
firebase.messaging().deleteToken()
.catch(error => {
console.log("Delected token error ", error)
})
}
After getting permission from the user we will create listeners for listen notification.
createNoitificationListeners = (onRegister, onNotification, onOpenNotification) => {
// This listener triggered when notification has been received in foreground
this.notificationListener = firebase.notifications().onNotification((notification) => {
onNotification(notification)
})
// This listener triggered when app is in backgound and we click, tapped and opened notifiaction
this.notificationOpenedListener = firebase.notifications()
.onNotificationOpened((notificationOpen) => {
console.log(notificationOpen)
if (notificationOpen) {
const notification = notificationOpen.notification
onOpenNotification(notification)
this.removeDelieveredNotification(notification)
}
})
// This listener triggered when app is closed and we click,tapped and opened notification
firebase.notifications().getInitialNotification()
.then(notificationOpen => {
if (notificationOpen) {
const notification = notificationOpen.notification
onOpenNotification(notification)
this.removeDelieveredNotification(notification)
}
})
// Triggered for data only payload in foreground
this.messageListener = firebase.messaging().onMessage((message) => {
onNotification(message)
})
// This listener triggered when new token
this.onTokenRefreshListener = firebase.messaging().onTokenRefresh(fcmToken => {
console.log("FCM new token: ", fcmToken)
onRegister(fcmToken)
})
}
Read More: Implement Push Notification with Firebase in React Native
Create Android Notification Channel
As of Android 8.0 (API Level 26), notifications must specify a Notification Channel or they will not appear. To allow React Native App Developers for Integrating Firebase to work seamlessly across all versions of Android, we will create buildChannel()
before we build notification.
buildChannel = (obj) => {
return new firebase.notifications.Android.Channel(
obj.channelId, obj.channelName,
firebase.notifications.Android.Importance.High)
.setDescription(obj.channelDes)
}
Build channel in android accepts three parameters channelId
, name
and importance
.
Now, we’ll add buildNotification() method which will build a notification when a notification is received:
buildNotification = (obj) => {
console.log(obj)
firebase.notifications().android.createChannel(obj.channel)
const notification = new firebase.notifications.Notification()
.setSound(obj.sound)
.setNotificationId(obj.dataId)
.setTitle(obj.title)
.setBody(obj.content)
.setData(obj.data)
.android.setChannelId(obj.channel.channelId)
.android.setLargeIcon(obj.largeIcon)
.android.setSmallIcon(obj.smallIcon)
.android.setColor(obj.colorBgIcon)
.android.setPriority(firebase.notifications.Android.Priority.High)
.android.setVibrate(obj.vibrate)
.android.setAutoCancel(true)
return notification
}
Let's create one function that displays notifications when a notification arrives.
displayNotification = (notification) => {
firebase.notifications().displayNotification(notification)
.catch(error => { console.log("Display Notification error", error) })
}
Whenever we open a notification and displays a notification after that we need to remove delivered notification so, we create
removeDelieveredNotification()
removeDelieveredNotification = (notification) => {
firebase.notifications()
.removeDeliveredNotification(notification.notificationId)
}
The Purpose of this tutorial is to schedule notification so, Let's create scheduleNotificaion()
scheduleNotification = (notification, datetime) => {
const date = new Date(datetime)
firebase.notifications()
.scheduleNotification(notification, { fireDate: date.getTime() })
}
So, Final FCMService.js
looks like this
Before proceeding further Please install this dependency
$ npm install react-native-elements react-native-modal-datetime-picker moment @react-native-community/datetimepicker react-native-vector-icons
So, we have created one file under src
folder scheduleReminder.js
Let's write below code into scheduleReminder.js
file
On componentDidMount()
we have register our fcmservice and link listener callback function we have link three function onRegister()
, onNotification()
and onOpenNotification()
.
onRegister
function we have got the user permission, onNotification
function called when our app is opened and any notification arrives that time onNotification function creates a notification and displays the notification and onOpenNotification
function called whenever you tap and open the notification.
We get time, title and description from the user to schedule a reminder, before a schedule reminder we need to create a notification object by using buildNotification()
of FCMService because a FCMService's scheduleNotification()
function accepts a parameter as notification object and date & time.
After configuring all things now it's time to test the app
Find the source code in the Github repo here.
Top comments (3)
Hi ,
It's not with the rnfirebase v6 right ? with @@react-native-firebase/messaging' ......
Hi,
I need firebase notification code which includes all three types of notifications like foreground, background and quite state. if you have please send or send repo link
thanks
Things have changed and here's a link to help people from now on:
notifee.app/react-native/docs/trig...