Ionic

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Share your learning

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.
Firebase Cloud Messaging (FCM) is a powerful and efficient platform for sending push notifications to mobile devices. When combined with the Ionic framework, it offers a seamless way to engage and interact with users through real-time notifications. 

In this tutorial, we will explore the integration of Firebase Cloud Messaging with the latest version of the Ionic framework, covering all the necessary steps from setup to implementation.

Prerequisites

Before we dive into the integration process, ensure you have the following prerequisites in place:

  1. Node.js and NPM: Make sure you have Node.js and NPM installed on your development machine. You can download them from the official Node.js website.
  2. Ionic CLI: Install the Ionic CLI by running the following command in your terminal:
    Shell
npm install -g @ionic/cli
  1. Firebase Account: Create a Firebase account (if you don’t have one) and set up a new project in the Firebase console.

Step 1: Set Up Firebase Project

  1. Create a new project in the Firebase console and follow the setup instructions.
  2. Add android/ios app to your firebase project.
  3. Download the google-services.json file and paste to android/app directory. Here ios configuration is little bit different, for ios check this article.
  4. Add web app to your Firebase project.
  5. Then in the next step you will find the Firebase credentials, copy and paste to your src/envrionments directory.

Step 2: Create an Ionic App

  1. Open your terminal and navigate to the directory where you want to create your Ionic app.
  2. Generate a new Ionic app using the Ionic CLI:
ionic start FCMApp blank

Navigate to the project directory:

cd FCMApp

Step 3: Install Required Dependencies

  1. Install the Firebase and AngularFire packages:
npm install firebase @angular/fire

Step 4: Configure Firebase in Ionic App

  1. Open the src/environments/environment.ts file and add your Firebase configuration:
export const environment = {

  production: false,

  firebaseConfig: {
    apiKey: 'YOUR_API_KEY',
    authDomain: 'YOUR_AUTH_DOMAIN',
    projectId: 'YOUR_PROJECT_ID',
    storageBucket: 'YOUR_STORAGE_BUCKET',
    messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
    appId: 'YOUR_APP_ID',
  },
};
Import and configure AngularFireModule in the src/app/app.module.ts file:
import { AngularFireModule } from '@angular/fire';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
  ],
  // ...
})

export class AppModule {}

Step 5: Implement FCM push notifications with Ionic application

  1. Create a service to handle push notifications. Generate a new service using the Ionic CLI:
ionic generate service Fcm

Open the src/app/fcm.service.ts file and implement the service:

import { Injectable } from '@angular/core';
import { AngularFireMessaging } from '@angular/fire/messaging';
import { mergeMapTo } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})

export class FcmService {

  constructor(private afMessaging: AngularFireMessaging) {}

  requestPermission() {
    return this.afMessaging.requestToken;
  }

  receiveMessages() {
    return this.afMessaging.messages;
  }

  listenToNotifications() {
    return this.afMessaging.tokenChanges.pipe(
      mergeMapTo(this.afMessaging.messages)
    );
  }
}

Step 6: Test FCM Notifications

  1. Open the src/app/app.component.ts file and modify it to use the FcmService:
    typescript
import { Component, OnInit } from '@angular/core';
import { FcmService } from './fcm.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
})

export class AppComponent implements OnInit {

  constructor(private fcmService: FcmService) {}

  ngOnInit() {

    this.fcmService.requestPermission().subscribe(
      (token) => {
        console.log('Permission granted! Token:', token);
      },

      (error) => {
        console.error('Permission denied:', error);
      }
    );

    this.fcmService.receiveMessages().subscribe((message) => {
      console.log('Received message:', message);
    });
  }
}

Step 7: Handle FCM push notifications with Ionic

  1. To handle notifications while the app is in the foreground, add the following code to the src/app/app.component.ts file:
    typescript
import { Component, OnInit } from '@angular/core';
import { FcmService } from './fcm.service';
import { ToastController } from '@ionic/angular';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
})

export class AppComponent implements OnInit {

  constructor(
    private fcmService: FcmService,
    private toastController: ToastController
  ) {}

  ngOnInit() {
    // ... (previous code)

    this.fcmService.listenToNotifications().subscribe((notification) => {
      this.presentToast(notification.notification.body);
    });
  }

  async presentToast(message: string) {

    const toast = await this.toastController.create({
      message,
      duration: 3000,
      position: 'bottom',
    });
    toast.present();
  }
}

Step 8: It’s time to test the App

  1. Run your Ionic app on a device or emulator using the following command:
    shell
ionic capacitor run android
  1. Replace android with ios for iOS devices.
  2. Grant permission for notifications when prompted.
  3. Use the Firebase console to send a test notification to your app.

Congratulations! You have successfully integrated Firebase Cloud Messaging with your Ionic app. You can now send and receive push notifications and handle them in real-time.

Conclusion

In this tutorial, we explored the process of integrating FCM (Firebase Cloud Messaging) push notifications with ionic framework. We covered setting up a Firebase project, configuring Firebase in an Ionic app, implementing push notifications, and handling notifications.

By following these steps, you can enhance user engagement and provide a richer experience to your Ionic app users through real-time notifications.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

8 months ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

8 months ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

9 months ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

9 months ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

9 months ago

Resolving the ‘Uncaught TypeError’ in jQuery AJAX: Understanding and Fixing the ‘append’ Interface FormData Error

Uncaught TypeErrror: append called on an object that does not implement interface FormData. JQuery has…

9 months ago