What is a push notification? And why it matters?

Push notification is a message that pops-up on your mobile device even when you are not using the app. For app publishers, it is a gateway to speak directly with app users.  Examples include getting a notification when a transaction is performed or getting a new offer from your online retailer – these notifications popup only for Apps that are previously installed on the device.

According to a survey, implementing push notification improves app engagement by 88%. Push notification was introduced to attract users to return to an application. The survey mentioned that the retention rate of an app increased by 4 to 10x. 

This blog will guide you to implement push notification using Firebase in React Native for iOS devices.

Shivani Sisode

Shivani Sisode

Software Developer

Neha Akhade

Neha Akhade

Mobile App Developer

Requirements:

  1. React Native Project
  2. Xcode Version >= 10.x
  3. Apple Developer license
  4. Physical iOS device
Workflow of Push Notifications

Following are the important steps to be performed:

Step 1. Create Certificate needed for push notification

 iOS: To start using push notification with iOS device following certificates are mandatory:

  1. Login to https://developer.apple.com/
  2. Go to Certificate ID’s and profiles
  3. Go to Identifiers
  4. Select app Id’s
    1. Click on + to create new app id
    2. Enter name of your App
    3. Enter Bundle ID(same as XCode bundle Identifier)
      1. Go to Xcode
      2. General->Identity->Bundle Identifier
    4. Select Push Notification
    5. Click on Continue
    6. Click on Register and then Done
  5. Go Back to App Id’s
    1. Select your app from App Id’s
    2. Click on Edit
    3. Under Push Notification Section
      1. Select  Development SSL Certificate => For Development or
      2. Select  Production  SSL Certificate=> For Production.
    4. Click on Create Certificate
    5. Click on Continue
    6. Now, upload Signing Certificate.
      1. Create the Signing Certificate needed for Apple Push Notification Service SSL. 
        1. Go to Keychain Access on your Desktop
          1. Tab on Keychain Access->Certificate Assistant
          2.  Select “Request a Certificate From a Certificate Authority”
          3. Enter Email Address
          4. Select Save to disk
          5. Click on Continue and save the file
        2. Choose .csr file we created in previous topic.
        3.  Download your Certificate
  6. To Convert .csr file to .p12 file
    1. Double Click on recently generated .cer file.
    2. If you have previously created .csr file.
      1. Go to Keychain Access on your Desktop
      2.  Go to Certificates
      3.  Select your certificate, right-click and choose to export in .p12 format. 
  7. Enable Capabilities
    1. In Xcode, enable the following capabilities:
      1. Push Notifications
      2. Background modes > Remote notifications

Step 2. Firebase Setup

  1. Login to https://console.firebase.google.com
  2. Click on Add Project (Existing User) / Click on Create Project (New User)
    1. Enter your new Project Name, Project Id and Region.
    2. Click on Continue button
    3. Now you are on Homepage
  3. Click on iOS option
    1. Enter Bundle ID(same as xcode bundle Identifier)
    2. Enter App nickname and App Store ID
    3. Click on Register  app and then Done
  4. Download GoogleService-Info.plist file and add into your root folder of your project.

Step 3. To Initialize firebase into an existing project

1.Add library:
For React Native firebase(V5.x.x):

npx install --save react-native-firebase

Or

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

For React Native Firebase(V6.x.x):

yarn add @react-native-firebase/app

For users on React Native >= 0.60, the module will be automatically linked to your project.

2.Add following into your existing project:

Common for React Native Firebase(V5.x.x and V6.x.x):

a.Add following line at the top of ios/[YOUR APP NAME]/AppDelegate.m file:

@import Firebase;

b.Add the following line at beginning of didFinishLaunchingWithOptions:(NSDictionary*)launchOptions method :

if ([FIRApp defaultApp] == nil) {
[FIRApp configure];
}

3.Make your pods up-to-date in podfile:
For React Native firebase(V5.x.x):
1.Add following pod:

pod 'Firebase/Core'

2.Run

pod install

For React Native firebase(V6.x.x):

$ cd ios/
$ pod install --repo-update

     

Step 4. To Make use of Firebase Cloud Messaging

For React Native firebase(V5.x.x):
1.Add following pod:

pod ‘Firebase/Messaging'

2.Run

pod install

For React Native firebase(V6.x.x):

yarn add @react-native-firebase/messaging
cd ios/ && pod install

Step 5. Setting up the application to get a push notification

While setting up you will come across the following terms:

  1. Message types: There are two types of messages handled by FCM:
    1. Data messages: Data messages are used to handle data along with the notification.
    2. Notification messages: Notification messages are a type in which FCM automatically triggers a message on the user’s device.
  2. Device Registration Token: During the initial phase of your app, the FCM SDK generates a device registration token, which is responsible to get a notification on your device. If the user initializes the app after clearing app data or uninstalls the app, the device registration token is regenerated. 

Step 6. Implementation

Add following functions in app.js to receive a push notification on mobile:

import React, {Component} from 'react';
import {StyleSheet, Text, View, Alert, AsyncStorage} from 'react-native';
import firebase from 'react-native-firebase';

export default class App extends Component{

  async componentDidMount() {
    this.checkPermission();
    this.createNotificationListeners();
  }

  componentWillUnmount() {
    this.notificationListener;
    this.notificationOpenedListener;
  }

  //Check whether Push Notifications are enabled or not
  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
      this.getToken();
    } else {
      this.requestPermission();
    }
  }

  //Get Device Registration Token
  async getToken() {
    let fcmToken = await AsyncStorage.getItem('fcmToken');
    if (!fcmToken) {
      fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
        console.log('fcmToken:', fcmToken);
        await AsyncStorage.setItem('fcmToken', fcmToken);
      }
    }
  }

  //Request for Push Notification
  async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // If user allow Push Notification
      this.getToken();
    } catch (error) {
      // If user do not allow Push Notification
      console.log('Rejected');
    }
  }

  async createNotificationListeners() {
    
    // If your app is in Foreground
   
    this.notificationListener = firebase.notifications().onNotification((notification) => {
        const localNotification = new firebase.notifications.Notification({
          show_in_foreground: true,
        })
        .setNotificationId(notification.notificationId)
        .setTitle(notification.title)
        .setBody(notification.body)

        firebase.notifications()
          .displayNotification(localNotification)
          .catch(err => console.error(err));
    });


    //If your app is in background

    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
      const { title, body } = notificationOpen.notification;
      console.log('onNotificationOpened:');
      Alert.alert(title, body)
    });


    // If your app is closed

    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
      console.log('getInitialNotification:');
    }

    // For data only payload in foreground

    this.messageListener = firebase.messaging().onMessage
((message) => {
      //process data message
      console.log("Message", JSON.stringify(message));
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Push Notification Demo</Text>
        <Text style={styles.instructions}>By Neova Solutions..</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});
 

To test your application you can send notification using Firebase Console.

Cheers ! We are Done.

I hope this blog helped you implement push notification using firebase for your React native iOS Apps. 

At Neova, we have an expert team of react native developers that are eager to work on the next big mobile app. Feel free to reach us at sales@neovatechsolutions.com for any queries.

Source Code:

https://gitlab.com/neovasolutions/react-native-firebase-notifications

More details:

https://rnfirebase.io/

https://firebase.google.com/docs/ios/setup

Headquarter

4701 Patrick Henry Drive,
Bldg. 16, Suite 106, Santa Clara, California 95054
781-640-0588
sales@neovatechsolutions.com

Development Center

P3-603, Pentagon Tower,
Magarpatta City, Hadapsar, Pune, Maharashtra 411028
960-702-3233