Day 7: Integrating Push Notifications with Firebase Cloud Messaging (FCM)


In this tutorial, you’ll learn how to set up Firebase Cloud Messaging and integrate it with your React Native app. By the end of today’s lesson, you’ll be able to send and receive notifications, even when the app is in the background or closed.


What You Will Learn Today:

  1. Setting up Firebase and configuring FCM
  2. Integrating Firebase in your React Native app
  3. Registering for push notifications
  4. Sending test notifications from the Firebase Console
  5. Handling notification events in React Native

Step 1: Setting Up Firebase and Configuring FCM

Before you can integrate Firebase with your app, you’ll need to create a Firebase project and configure FCM.

  1. Go to the Firebase Console and create a new project.
  2. Click Add app and select Android. (iOS setup is similar and can be done afterward.)
  3. Follow the instructions to register your app:
  • Package Name: Enter your app’s package name (e.g., com.yourappname).
  1. Download the google-services.json file and place it in your project’s android/app directory.

Configuring Firebase in Android

  1. Open your android/build.gradle file and add the following classpath in the dependencies section:
classpath 'com.google.gms:google-services:4.3.8'
  1. Open android/app/build.gradle and add the following line at the bottom of the file:
apply plugin: 'com.google.gms.google-services'

This configuration integrates Firebase into your Android app. For iOS, you’ll need to download the GoogleService-Info.plist and follow Firebase’s iOS setup instructions.

See also  Day 8: Progressive Enhancement – Making the App Usable in Low-Data Scenarios

Step 2: Installing Firebase and FCM Dependencies

To enable push notifications, you’ll need to install Firebase packages for React Native, including @react-native-firebase/app and @react-native-firebase/messaging.

  1. Install the necessary Firebase packages:
npm install @react-native-firebase/app @react-native-firebase/messaging
  1. For iOS, navigate to the ios folder and install CocoaPods dependencies:
cd ios
pod install
cd ..

Explanation:

  • @react-native-firebase/app: The core Firebase package that initializes Firebase in your app.
  • @react-native-firebase/messaging: Handles cloud messaging features, allowing you to receive push notifications from FCM.

Step 3: Registering for Push Notifications

Let’s set up the app to request permission for notifications and register the device with FCM.

  1. Create a new file called NotificationService.js:
touch NotificationService.js
  1. Open NotificationService.js and set up notification permissions and listeners:
import messaging from '@react-native-firebase/messaging';
import { Alert } from 'react-native';

// Request user permission for notifications
export async function requestUserPermission() {
  const authStatus = await messaging().requestPermission();
  const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
                  authStatus === messaging.AuthorizationStatus.PROVISIONAL;

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

// Get the FCM token and save it
export async function getFcmToken() {
  const token = await messaging().getToken();
  if (token) {
    console.log('FCM Token:', token);
  } else {
    console.log('Failed to get FCM token');
  }
}

// Listen to notification events
export function notificationListener() {
  // Foreground notifications
  messaging().onMessage(async remoteMessage => {
    Alert.alert('New Notification!', remoteMessage.notification?.body);
  });

  // Background and quit notifications
  messaging().setBackgroundMessageHandler(async remoteMessage => {
    console.log('Notification in background:', remoteMessage);
  });
}

Explanation:

  • requestUserPermission: Asks the user for notification permissions. Without permission, notifications won’t be delivered.
  • getFcmToken: Retrieves the device’s unique FCM token, which is required for targeting specific devices with notifications.
  • notificationListener: Listens for notification events when the app is in the foreground or background.

Step 4: Integrating NotificationService with the App

Now let’s integrate NotificationService in your main app component to request permission and start listening for notifications.

  1. Open App.js and import the notification functions:
import React, { useEffect } from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from './store/store';
import { requestUserPermission, getFcmToken, notificationListener } from './NotificationService';
import LoginScreen from './LoginScreen';
import HomeScreen from './HomeScreen';
import { useSelector } from 'react-redux';

function AppContent() {
  const token = useSelector((state) => state.auth.token);

  useEffect(() => {
    // Request notification permission and register token
    requestUserPermission();
    getFcmToken();

    // Set up notification listeners
    notificationListener();
  }, []);

  return token ? <HomeScreen /> : <LoginScreen />;
}

export default function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <AppContent />
      </PersistGate>
    </Provider>
  );
}

Explanation:

  • useEffect: Runs on app load to request notification permission, register the device token, and set up notification listeners.
  • requestUserPermission, getFcmToken, notificationListener: These functions initialize FCM, obtain the token, and set up listeners.
See also  Day 9: Integrating Product Reviews and Ratings

Step 5: Sending Test Notifications from Firebase Console

Now that your app is set up to receive notifications, you can test by sending a notification from the Firebase Console.

  1. Go to your Firebase project in the Firebase Console.
  2. In the Cloud Messaging section, click on Send your first message.
  3. Fill in the message details:
  • Notification title: Enter any title (e.g., “Hello”).
  • Notification text: Enter any text (e.g., “This is a test notification”).
  1. Under Target, choose User segment to send to all users or select Single device and enter the FCM token from the console log.
  2. Click Send message to test your notification.

You should receive the notification on your device or emulator.


Step 6: Handling Notifications in Different States

React Native Firebase automatically handles notifications based on the app’s state. Here’s how notifications are managed:

  • Foreground: The app is active and in the foreground. Notifications can be displayed using Alert or any other in-app message.
  • Background: The app is running but not in focus. Notifications appear in the device’s notification tray.
  • Killed (Quit): The app is not running. Notifications will still appear in the notification tray.

These notifications can be customized further depending on your app’s requirements.


Step 7: Recap and Summary

In today’s tutorial, you learned how to integrate push notifications with Firebase Cloud Messaging in a React Native app. Here’s a quick summary of what you’ve done:

  • Set up a Firebase project and configured FCM.
  • Installed Firebase packages for React Native.
  • Created a NotificationService to manage FCM token registration and notification listeners.
  • Integrated notification functionality in your app, allowing it to receive push notifications.
  • Sent a test notification from the Firebase Console to verify everything works correctly.
See also  Day 7: Securing User Authentication and Authorization with Role-Based Access Control (RBAC)

With FCM integrated, you can now send notifications to keep users engaged and informed.


Next Up: Day 8 – Implementing Deep Linking in React Native

In Day 8, we’ll explore deep linking, which allows you to link users directly to specific content or pages within your app, enhancing the user experience and boosting engagement.

Stay tuned for more advanced features tomorrow!


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.