Sending a push Notification from Firebase

nagabhushan_adiga_a383471

Nagabhushan Adiga

Posted on July 24, 2024

Sending a push Notification from Firebase

Here a comprehensive guide on how to send push notifications in a React Native application using Firebase Cloud Messaging (FCM).

Prerequisites

  1. Node.js and npm: Make sure you have Node.js and npm installed.
  2. React Native CLI: Install React Native CLI if you haven't already.
   npm install -g react-native-cli
Enter fullscreen mode Exit fullscreen mode
  1. Firebase Project: Create a project on the Firebase Console.
  2. Firebase CLI: Install Firebase CLI to configure your project.
   npm install -g firebase-tools
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Guide

1. Create and Configure Firebase Project

  • Go to the Firebase Console.
  • Click on "Add Project" and follow the prompts to create a new project.
  • Navigate to "Cloud Messaging" and copy the Server key and Sender ID. These will be needed later.

2. Set Up React Native Project

  • Initialize a new React Native project:
  npx react-native init FirebasePushNotification
  cd FirebasePushNotification
Enter fullscreen mode Exit fullscreen mode

3. Install Required Packages

  • Install Firebase and FCM libraries:
  npm install @react-native-firebase/app @react-native-firebase/messaging
Enter fullscreen mode Exit fullscreen mode

4. Configure Firebase with Your React Native App

  • iOS Configuration:

    • Navigate to the Firebase Console, select your project, and go to "iOS App."
    • Register your app with the iOS bundle ID.
    • Download the GoogleService-Info.plist file and place it in the ios/ directory of your React Native project.
  cp GoogleService-Info.plist ios/
Enter fullscreen mode Exit fullscreen mode
  • Open the ios/YourProjectName.xcworkspace in Xcode.
  • Drag and drop GoogleService-Info.plist into your project.
  • Ensure FirebaseAppDelegateProxyEnabled is set to YES in the Info.plist.

    • Android Configuration:
  • Navigate to the Firebase Console, select your project, and go to "Android App."

  • Register your app with the Android package name.

  • Download the google-services.json file and place it in the android/app directory.

  cp google-services.json android/app/
Enter fullscreen mode Exit fullscreen mode
  • Modify android/build.gradle to include the Google services classpath:

    dependencies {
        classpath 'com.google.gms:google-services:4.3.10'
    }
    
  • Update android/app/build.gradle to apply the Google services plugin:

    apply plugin: 'com.google.gms.google-services'
    

5. Implement Notification Logic

  • iOS Setup:

    • Open ios/YourProjectName/AppDelegate.m.
    • Import Firebase and configure it:
    #import <Firebase.h>
    

    In the application:didFinishLaunchingWithOptions method, configure Firebase:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        [FIRApp configure];
        return YES;
    }
    
  • Android Setup:

    • Modify android/app/src/main/java/com/yourprojectname/MainApplication.java to include Firebase:
    import io.invertase.firebase.app.ReactNativeFirebaseAppPackage;
    

    Update the getPackages method:

    @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
            new ReactNativeFirebaseAppPackage()
        );
    }
    

6. Implement Notification Handling in React Native

  • Import and configure messaging in your React Native code:
  import messaging from '@react-native-firebase/messaging';

  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);
    }
  }

  useEffect(() => {
    requestUserPermission();

    const unsubscribe = messaging().onMessage(async remoteMessage => {
      console.log('A new FCM message arrived!', JSON.stringify(remoteMessage));
    });

    return unsubscribe;
  }, []);
Enter fullscreen mode Exit fullscreen mode

7. Send a Test Notification

  • Using Firebase Console:

    • Navigate to the "Cloud Messaging" section of your Firebase project.
    • Click "Send your first message" and fill in the required fields. Choose your target device (or all devices).
    • Click "Send" to dispatch the notification.
  • Using Firebase Admin SDK (Server-side):

    • Set up Node.js and install the Firebase Admin SDK:
    npm install firebase-admin
    
    • Initialize the Admin SDK and send a notification:
    const admin = require('firebase-admin');
    const serviceAccount = require('./path/to/serviceAccountKey.json');
    
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: 'https://<your-database-name>.firebaseio.com'
    });
    
    const message = {
      notification: {
        title: 'Hello',
        body: 'World'
      },
      token: '<device-token>'
    };
    
    admin.messaging().send(message)
      .then((response) => {
        console.log('Successfully sent message:', response);
      })
      .catch((error) => {
        console.log('Error sending message:', error);
      });
    

Conclusion

You now have a React Native app set up to receive push notifications via Firebase Cloud Messaging. Ensure you handle permissions, foreground and background notifications correctly in your code to provide a seamless user experience.

💖 💪 🙅 🚩
nagabhushan_adiga_a383471
Nagabhushan Adiga

Posted on July 24, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related