Day 6: Sending Notifications When a New Message Is Received


Today, you’ll implement push notifications to alert users when they receive a new message in the chat app. This will be done using Firebase Cloud Messaging (FCM) for real-time notifications.

What You Will Do Today:

  1. Set up Firebase Cloud Messaging for the chat app.
  2. Configure notifications for new messages.
  3. Test notifications on Android and iOS.

Step 1: Set Up Firebase Cloud Messaging

  1. Install Firebase Messaging: npm install @react-native-firebase/messaging
  2. Link Native Modules: For iOS, install CocoaPods dependencies: cd ios pod install cd ..
  3. Configure Firebase Messaging:
    • Add the google-services.json file for Android (if not already added).
    • Add the GoogleService-Info.plist file for iOS (if not already added).

Step 2: Configure Notifications in the App

  1. Request Notification Permissions: Add the following to your App.js:
import React, { useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import { Alert, Platform } from 'react-native';

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

  if (enabled) {
    console.log('FCM Permission granted.');
  } else {
    Alert.alert('Permission denied', 'You will not receive notifications.');
  }
};

const handleNotifications = () => {
  messaging().onMessage(async (remoteMessage) => {
    Alert.alert('New Message', remoteMessage.notification.body);
  });

  messaging().setBackgroundMessageHandler(async (remoteMessage) => {
    console.log('Background Message:', remoteMessage);
  });
};

export default function App() {
  useEffect(() => {
    requestFCMPermission();
    handleNotifications();
  }, []);

  return <YourNavigationStack />;
}
  1. Generate an FCM Token: Add this to the App.js useEffect:
useEffect(() => {
  const getToken = async () => {
    const token = await messaging().getToken();
    console.log('FCM Token:', token);
  };

  getToken();
}, []);

This token uniquely identifies the user’s device for push notifications.

    See also  Day 9: Implementing In-App Purchases in React Native

    Step 3: Trigger Notifications for New Messages

    1. Modify Firestore Rules: Ensure your Firestore rules allow the necessary operations for messages.
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /messages/{messageId} {
          allow read, write: if request.auth != null;
        }
      }
    }
    
    1. Set Up Firebase Functions: Use Firebase Functions to send push notifications when a new message is added to the messages collection.
      • Install the Firebase CLI if not already done: npm install -g firebase-tools
      • Initialize Firebase Functions: firebase init functions
      • Add the following code to functions/index.js:
    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    exports.sendNotificationOnNewMessage = functions.firestore
      .document('messages/{messageId}')
      .onCreate(async (snapshot, context) => {
        const message = snapshot.data();
    
        const payload = {
          notification: {
            title: `New Message from ${message.userName}`,
            body: message.text,
          },
        };
    
        try {
          await admin.messaging().sendToTopic('chat', payload);
          console.log('Notification sent successfully');
        } catch (error) {
          console.error('Error sending notification:', error);
        }
      });
    
    1. Deploy the function: firebase deploy --only functions
    2. Subscribe to Topic: In your app, subscribe the user to the chat topic:
    useEffect(() => {
      messaging()
        .subscribeToTopic('chat')
        .then(() => console.log('Subscribed to chat topic'));
    }, []);
    

    Step 4: Test Notifications

    1. Send a Test Notification:
      • Go to the Firebase Console.
      • Navigate to Cloud Messaging > Send your first message.
      • Send a message to the chat topic and confirm it appears on the device.
    2. Test with a New Message:
      • Add a new message in the chat.
      • Verify that a notification is triggered and displayed.

    Step 5: Handle Background and Killed App States

    1. Use the following handlers for background and killed app states:
    useEffect(() => {
      messaging().onNotificationOpenedApp((remoteMessage) => {
        console.log('Notification caused app to open:', remoteMessage);
      });
    
      messaging()
        .getInitialNotification()
        .then((remoteMessage) => {
          if (remoteMessage) {
            console.log('Notification caused app to open from quit state:', remoteMessage);
          }
        });
    }, []);
    

    Summary

    Today, you implemented push notifications using Firebase Cloud Messaging (FCM). Users are now alerted in real-time whenever they receive a new message, even if the app is running in the background or is closed.

    See also  Day 7: Securing Your App with Firebase Rules and Authentication

    Tomorrow, you’ll work on displaying message status (sent, delivered, read) to enhance the chat experience.


    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.