How to Implement Push Notifications for iOS and Android In React Native
Push notifications have a powerful impact on the conversions, engagement, and retention on your website. You can use them in different ways and forms to promote your valuable content, direct users to other channels, announce news and offers.
According to Localytics, push notifications boost app engagement by 88%. The key here is to find the right user touchpoints and make these notifications relevant.
In this article, we want to show how to setup and customize push notifications for iOS and Android in React Native.
Let's get straight to the point.
Setting push notifications in React Native
To implement push notifications in a React Native application, you can use the react-native-push-notification library, that works both for iOS and Android.
This library allows you to set up 4 types of notifications:
- local notifications
- noisy remote push notifications
- silent remote push notifications
- mixed remote push notifications
Local push notifications are sent from React Native applications and appear in the notification center, where they remain until the user removes them. This type of notifications also provides a set of different features, that allow you to create notifications with a custom design.
Remote push notifications are sent from the server, such as Apple Push Notification Service (APNS) or Google Cloud Messaging Service (GCM).
Getting started with React Native push notification library
First of all, you have to set up the library using npm.
As this library uses native modules, you also have to manually install the library for iOS and Android.
Follow the instructions described in Installations sections , iOS manual Installation, and Android manual installation.
For initial configuration of notifications, call the method PushNotification.configure() and pass it the object with the following properties:
(Optional) is called when Token is generated (iOS and Android).
`onRegister: function(token) {
console.log( 'TOKEN:', token );
},`
(Required) is called when any notification is opened or received. Here you can process the notification, as the object with notification data is passed to the function.
onNotification: function(notification) {}
In Android, this property is optional for local notifications and required - for remote ones.
senderID: "GCM SENDER ID"
Permissions for iOS (optional)
permissions: {
alert: true,
badge: true,
sound: true
}
(Optional) installed in true
by default
popInitialNotification: true
It defines whether the request for permissions (iOS) and Token (Android and iOS) will be pulled. It's true by default. If you want to set it as false
, you need to call PushNotificationsHandler.requestPermissions()
later.
requestPermissions: true
Notifications should be configured beyond React Native lifecycle, in the entry point of JavaScript code.
Find the file index.js (index.android.js, index.ios.js) in the root folder of your project.
Look at the call function registerComponent() to find the component of the highest level. In this case, it's App.
Gain clarity with your project!
Let's create the folder for services for our application './src/services' with two files - index.js and pushNotification.js
pushNotifications.js:
import PushNotification from 'react-native-push-notification';
import { PushNotificationIOS } from 'react-native';
const configure = () => {
PushNotification.configure({
onRegister: function(token) {
//process token
},
onNotification: function(notification) {
// process the notification
// required on iOS only
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true,
});
};
export {
configure,
};
Index.js:
import * as pushNotifications from './pushNotifications';
export {
pushNotifications,
}
Now let's import the service of notifications in the file with the highest level component and call the configuration before React Native lifecycle.
import React from 'react';
import { Provider } from 'react-redux';
import { pushNotifications } from './src/services';
import store from './src/store';
import AppContainer from './src/AppContainer';
pushNotifications.configure();
const App = () => (
<Provider store={store}>
<AppContainer />
</Provider>
);
export default App;
Let's add the opportunity to call local notifications to our notification service. You need to call
PushNotification.localNotification(details: Object).
Now let's see the properties of details object, that is passed by the parameter for localNotification.
Only for Android:
id
- (optional). Real, unique whole 32-bit number, indicated as a string. By default: autogenerated unique identification.
ticker
– (optional) string, Notification Ticker
autoCancel
– (optional) Boolean, true by default. Boolean determines whether the notification is automatically hidden.
largeIcon
– (optional) default: "ic_launcher" (application icon). Big icon for notifications.
smallIcon
– (optional) default: "ic_notification". Small icon for notifications is generated from the label “ic_launcher”, that's why this auto-generated icon may be displayed incorrectly.
Small icon for notifications should have a transparent background with no colors.
Here is the example of the picture of a small icon.
Now let's add the small icon with the name ic_notification.png in android/app/src/main/res/mipmap-‘dpi’
Now the small icon notification will look like this:
bigText
– (optional) - has the same characteristics as in “message” property by default.
subText:
"This is a subText", – (optional) default: none
color
– // (optional) default: system default
On the previous screens, the color is set by default.
Now I have set the green color
vibrate
: true, – (optional) default: true
vibration
: 300, – vibration length in milliseconds, ignored if vibrate=false, default: 1000
tag
: 'some_tag', – (optional) adding tags to the message
group
: " some_group", – (optional) messages grouping
ongoing
: false, – (optional). If you set “true”, the message can`t be deleted from the notifications center. When you press notification, it disappears and the application is opened
repeatType
: 'day', – Repeating interval. Could be one of `week`, `day`, `hour`, `minute, `time`.
If the property repeatType is set as “time”, you need to use one more property:
repeat time
– the number of milliseconds between each interval.
For iOS:
alertAction
– (optional) can be used to specify the string that will appear below the notification, by default – ‘view’
category
– (optional) can be used to specify the notification actions to show for the notifications. The notification actions appear if you slide the notification towards the left. default: null
userInfo
: – (optional) default: null (object containing additional notification data)
Properties for iOS and Android:
title
– the name of the notification (optional, for iOS this is only used in apple watch, the title will be the app name on other iOS devices)
message
– (required) string, the text of the notification.
playSound
– (optional) Boolean. default: true. If you set “false”, the notification will be silent.
soundName
– (optional) The notification is noisy. Value of 'default' plays the default sound.
In android, add your custom sound file to [project_root]/android/app/src/main/res/raw
In iOS, add your custom sound file to the project Resources in xCode.
number
– (optional) Valid 32 bit integer specified as a string. default: none (Cannot be zero)
actions
: '["Accept", "Reject"]' – This is an array of strings where each string is a notification action that will be presented with the notification.
Thus, to call local notification, let`s add the following code to the file ./src/services/pushNotifications.js
//Here is the code, we have written before
//...
const localNotification = () => {
PushNotification.localNotification({
autoCancel: true,
largeIcon: "ic_launcher",
smallIcon: "ic_notification",
bigText: "My big text that will be shown when notification is expanded",
subText: "This is a subText",
color: "green",
vibrate: true,
vibration: 300,
title: "Notification Title",
message: "Notification Message",
playSound: true,
soundName: 'default',
actions: '["Accept", "Reject"]',
});
};
export {
configure,
localNotification,
};
To demonstrate the notification performance, add the button for calling local notification. file ./src/AppContainer.js
Result
In order to choose the right push notifications, read on to discover this list of 70+ ideas for your app development project.