React Native Push Notifications with Firebase

Study app for implementing Push Notifications with Firebase in a React Native mobile app.

Tutorial By Osledy Bazó Date: 11/12/19

In this tutorial we are going to implement Push Notifications in a React Native mobile aplicación, our notification backend will be in Firebase for ease of use, but you can use your own system.

First create a project in your Google Firebase Console https://console.firebase.google.com/

Also create your React Native project and enter it’s directory
react-native init RNPushNotifications

Adding Firebase to your app

Register your app in Firebase and follow the configuration steps for Android and for iOS.
Download your GoogleService-Info.plist and google-services.json. Don’t forget to place them in the correct folder for each platform

Android:

iOS:

Add and link the React Native Firebase package to your app

npm install react-native-firebase
react-native link react-native-firebase

Follow the installation instruction for the latest release here:

Android: https://rnfirebase.io/docs/v5.x.x/installation/android
iOS: https://rnfirebase.io/docs/v5.x.x/installation/ios

Generate APNS certificate for iOS Push Notifications

On iOS you need to Generate an APNS certificate in order to receive Push Notifications.
Apple Push Notification Service (commonly referred to as Apple Notification Service or APNS) is a platform service created by Apple Inc. that enables third party application developers to send push notifications to iOS users. You must have Paid Apple Developer account to create certificates.

  • Login to Apple developer account and click “Certificates, IDs & Profiles”
    (https://developer.apple.com/)

  • Select “Identifiers” form the left menu

  • Click the Plus (+) sign above the center list

  • Choose “App IDs” from the selection options

  • Fill out your Description, Bundle ID, and choose “Push Notifications” form the options.

  • Confirm your information and click “Register”

Generate a Certificate from Keychain Access

  • Launch the Keychain Access application in your Mac OS X and Select Keychain Access -> Certificate Assistant -> Request a Certificate From a Certificate Authority

  • Enter email address and check the ‘Saved to disk’ option, then click Continue

Generate a Development Certificate

  • Go back to developer account and select app from App IDs and click on it to Edit

  • Scroll Down to Push Notifications and click on Configure

  • Under Development SSL Certificate click Create Certificate

  • Choose the file you created in the previous step and click Continue

  • Download Development Certificate to finish process

Generate APNS .p12 certificate

  • Double click Development certificate generated in previous step to add it to Keychain Access. Go to Keychain Access, select login keychain and My Certificate from side menu. Find app certificate and right click to export it

  • Enter certificate name and click Save

  • Enter password for certificate and click OK

  • Enter your computer admin password to finish the process

These are all the steps to create a development certificate, now we continue to add PushNotifications to our app

Configuration iOS project

On Xcode go to your project settings, under Singing and Capabilities, add these two:

  • Push notifications

  • Background Modes — Check only Remote Notifications

Configuration Android project

  • In MainnApplication.java
// Add these
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;

public class MainApplication extends Application implements 
ReactApplication {
  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

    @Override
    protected List<ReactPackage> getPackages() {
  		List<ReactPackage> packages = new PackageList(this).getPackages();
    packages.add(new RNFirebasePackage());
    packages.add(new RNFirebaseMessagingPackage());
    packages.add(new RNFirebaseNotificationsPackage());
    return packages;
  }
}

  • In AndroidManifest.xml add the permissions
<manifest …>
  <uses-permission android:name=“android.permission.INTERNET” />
  <uses-permission android:name=“android.permission.RECEIVE_BOOT_COMPLETED” />
  <uses-permission android:name=“android.permission.VIBRATE” />
</manifest>
  • Set the application startup mode in activity properties
<manifest …><activity
          android:name=“.SplashActivity”android:launchMode=“singleTop”> <!— add this line —>
    </activity>
    <activity
        android:name=“.MainActivity”android:launchMode=“singleTask” <!— add this line —>
      />
    <activity android:name=“com.facebook.react.devsupport.DevSettingsActivity” android:launchMode=“singleTop” /> <!— agregar esta linea —>

</manifest>

If we want to schedule local notifications, we must also add the following

<manifest ...>
  ...
  <application ...>
    <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
    <receiver 
      android:enabled="true"
      android:exported="true"
android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
        <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </receiver>
    <receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true">
    <intent-filter>
      <action android:name="io.invertase.firebase.notifications.BackgroundAction"/>
    </intent-filter>
  </receiver>
  <service android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionsService"/>
  </application>
</manifest>

From Android 8.0 (API level 26) and higher, notification channels are compatible and recommended. FCM provides a default notification channel with basic settings. If you want to create and use your own default channel, you must configure default_notification_channel_id to the ID of the notification channel object as shown below; FCM will use this value when incoming messages do not explicitly establish a notification channel.

<manifest ...>
  ...
  <application ...>
    <meta-data  android:name="com.google.firebase.messaging.default_notification_channel_id"
      android:value="@string/default_notification_channel_id"/>
  </application>
</manifest>
  • Add the messaging service to the manifest:
<manifest …><application …>
    <service android:name=“io.invertase.firebase.messaging.RNFirebaseMessagingService”>
      <intent-filter>
        <action android:name=“com.google.firebase.MESSAGING_EVENT” />
      </intent-filter>
    </service>
  </application>
</manifest>

If you want to be able to react to messages that are only data when your application is in the background – for example, to show a heads-up notification – you must add the following:

<manifest ...>
  ...
  <application ...>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
  </application>
</manifest>

After having configured everything correctly we can test directly from the firebase console:

  • Go to the Cloud Messaging option in the left pane.
  • Click on Send your first message
  • Enter your test text, select the Android application to which you want to send the application and click Send.

Implementing FCM tokens in your app

Lets go to our App.js and add some code

After everything set up and configured for the Android and iOS (in Xcode), now, we have to implement the FCM push notification in React Native side using React Native Firebase module. Just open and edit App.js then add or modify these imports of Firebase, React Hooks useEffect, and React Native Alert.

import React, {Fragment,useEffect} from ‘react’;
import {
 SafeAreaView,
 StyleSheet,
 ScrollView,
 View,
 Text,
 StatusBar,
 Alert
} from ‘react-native’;
import firebase from ‘react-native-firebase’;

Implement the use effect function or method that run checkPermission and messageListener functions.

useEffect(() => {
 this.checkPermission();
 this.messageListener();
}, []);

Add a function to check the permissions.

checkPermission = async () => {
 const enabled = await firebase.messaging().hasPermission();
 if (enabled) {
   this.getFcmToken();
 } else {
   this.requestPermission();
 }
}

Add a function to get FCM token from the Firebase and show the token to the React Native Alert.

getFcmToken = async () => {
 const fcmToken = await firebase.messaging().getToken();
 if (fcmToken) {
  console.log(fcmToken);
  this.showAlert(‘Your Firebase Token is:’, fcmToken);
 } else {
  this.showAlert(‘Failed’, ‘No token received’);
 }
}

Add a function to request new permission to use Firebase Notification services.

requestPermission = async () => {
 try {
  await firebase.messaging().requestPermission();
  // User has authorised
 } catch (error) {
   // User has rejected permissions
 }
}

Add a function to listen to the incoming messages or Push Notification from the Firebase Cloud Messaging (FCM) then show them as an Alert when the App is open.

messageListener = async () => {
 this.notificationListener = firebase.notifications().onNotification((notification) => {
   const { title, body } = notification;
   this.showAlert(title, body);
 });

 this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
   const { title, body } = notificationOpen.notification;
   this.showAlert(title, body);
 });

 const notificationOpen = await firebase.notifications().getInitialNotification();
 if (notificationOpen) {
   const { title, body } = notificationOpen.notification;
   this.showAlert(title, body);
 }

 this.messageListener = firebase.messaging().onMessage((message) => {
  console.log(JSON.stringify(message));
 });
}

Add a function to show an alert with a title and message params.

showAlert = (title, message) => {
 Alert.alert(
  title,
  message,
  [
   {text: ‘OK’, onPress: () => console.log(‘OK Pressed’)},
  ],
  {cancelable: false},
 );
}

In the console, you will see the FCM toke, you can copy and paste it in the Firebase Console for your testings

 

Now you can send Push Notifications based on app platform, devices, dates registered, etc. Google Firebase has many options for sending these notifications.

© 2019 BOUNCING SHIELD ALL RIGHTS RESERVED #REMOTEWORK #NOMADLIFE
Siguenos