React Native Push Notifications with Firebase & Hooks 2020

Alameda Dev.
Feb 24, 2020 · 7 min read

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

Image for post
Image for post

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.

You can find the complete code here: https://github.com/uokesita/RNPushNotifications

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

Also, create your React Native project and enter its 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

Image for post
Image for post
Image for post
Image for post

Add and link the React Native Firebase package to your app.

yarn add @react-native-firebase/app
yarn add @react-native-firebase/messaging
cd ios ; pod install ; cd ..

Follow the installation instruction for the latest release here:

Android: https://rnfirebase.io/#2-android-setup
iOS: https://rnfirebase.io/#3-ios-setup

Generate APNS certificate for iOS Push Notifications

On iOS, you need to Generate an APNS certificate 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 a paid Apple Developer account to create certificates.

  • Log in to Apple developer account and click “Certificates, IDs & Profiles”
    (https://developer.apple.com/)
  • Select “Identifiers” form the left menu
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

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
Image for post
Image for post
  • Enter the email address and check the ‘Saved to disk’ option, then click Continue
Image for post
Image for post
Image for post
Image for post

Generate a Development Certificate

  • Go back to the developer account and select app from App IDs and click on it to Edit
Image for post
Image for post
  • Scroll Down to Push Notifications and click on Configure
Image for post
Image for post
  • Under Development SSL Certificate click Create Certificate
Image for post
Image for post
  • Choose the file you created in the previous step and click Continue
Image for post
Image for post
  • Download Development Certificate to finish process
Image for post
Image for post

Generate APNS .p12 certificate

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

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

As pointed by a nice commenter (Andrew Vo-Nguyen) you also need to add your .p12 certificate to Firebase > Project Settings > Cloud Messaging (Tab) > iOS app configuration > APNs Certificates. Thanks Andrew.

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

Configuration iOS project

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

Image for post
Image for post
Image for post
Image for post

iOS prevents messages containing notification (or 'alert') payloads from being displayed unless you have received explicit permission from the user.

This module provides a requestPermission method which triggers a native permission dialog requesting the user's permission:

import messaging from '@react-native-firebase/messaging';
...
useEffect(() => {
requestUserPermission();
}, []);

requestUserPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;

if (enabled) {
console.log('Authorization status:', authStatus);
}
}
...

The permissions API for iOS provides much more fine-grain control over permissions and how they're handled within your application. To learn more, view the advanced iOS Permissions documentation.

On Android, you do not need to request user permission. This method can still be called on Android devices; however, and will always resolve successfully.

Implementing FCM tokens in your app

Let’s 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";

Change the method that runs checks Permissions.

requestUserPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
getFcmToken() //<---- Add this
console.log('Authorization status:', authStatus);
}
}

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

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

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.
Image for post
Image for post
Image for post
Image for post

You can use the FCM token to test your notifications.

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

Click to watch the Video

Other functions

Foreground state messages

To listen to messages in the foreground, call the onMessage method inside of your application code. Code executed via this handler has access to React context and is able to interact with your application (e.g. updating the state or UI).

For example, the React Native Alert API could be used to display a new Alert each time a message is delivered’

import { Alert } from 'react-native';
...
useEffect(() => {
requestUserPermission();
const unsubscribe = messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
});
return unsubscribe;
}, []);
...

The remoteMessage property contains all of the information about the message sent to the device from FCM, including any custom data (via the data property) and notification data. To learn more, view the RemoteMessage API reference.

If the RemoteMessage payload contains a notification property when sent to the onMessage handler, the device will not show any notification to the user. Instead, you could trigger a local notification or update the in-app UI to signal a new notification.

Please see ther uses for background notifications here
https://rnfirebase.io/messaging/usage#foreground-state-messages

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

You can find the complete code here: https://github.com/uokesita/RNPushNotifications

Bouncing Shield is part of Alameda dev Team. If you have any questions, you can contact us at hola@alamedadev.com.
And https://alamedadev.com

Alameda Dev.

Specialized in Design and Development of Mobile Apps, Web with React Ecosystem

Alameda Dev.

Written by

¡Hola! We are a team 100% Remote. Specialized Development of Mobile Apps, Web and advanced software with React and ReactNative. www.alamedadev.com

Alameda Dev.

We are a small agency 100% Remote. Specialized in Design and Development of Mobile Apps, Web and advanced software with React Ecosystem.

Alameda Dev.

Written by

¡Hola! We are a team 100% Remote. Specialized Development of Mobile Apps, Web and advanced software with React and ReactNative. www.alamedadev.com

Alameda Dev.

We are a small agency 100% Remote. Specialized in Design and Development of Mobile Apps, Web and advanced software with React Ecosystem.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store