Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications
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:
- 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.
- Ionic CLI: Install the Ionic CLI by running the following command in your terminal:
Shell
npm install -g @ionic/cli
- 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
- Create a new project in the Firebase console and follow the setup instructions.
- Add android/ios app to your firebase project.
- Download the
google-services.json
file and paste toandroid/app
directory. Here ios configuration is little bit different, for ios check this article. - Add web app to your Firebase project.
- 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
- Open your terminal and navigate to the directory where you want to create your Ionic app.
- 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
- Install the Firebase and AngularFire packages:
npm install firebase @angular/fire
Step 4: Configure Firebase in Ionic App
- 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
- 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
- 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
- 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
- Run your Ionic app on a device or emulator using the following command:
shell
ionic capacitor run android
- Replace android with ios for iOS devices.
- Grant permission for notifications when prompted.
- 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.