/firebase-tutorials

How to set up Firebase Cloud Messaging (FCM)?

Learn how to set up Firebase Cloud Messaging (FCM) for Android and iOS with our step-by-step guide covering project creation, app integration, and server setup.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to set up Firebase Cloud Messaging (FCM)?

 

Step 1: Create a Firebase Project

 

  1. Go to the Firebase Console.
  2. Click on "Add Project" or select an existing project if you already have one.
  3. Follow the steps to create a project: give it a name, set up Google Analytics if needed, and click "Create Project."

 

Step 2: Add Firebase to Your App

 

  1. Once the project is created, navigate to the Project Overview page.
  2. Click on the Android or iOS icon to add Firebase to your app.
  3. For Android:
  • Register your app by entering the package name, and optionally, the app nickname and the debug signing certificate SHA-1.
  • Download the google-services.json file and place it in the app directory of your project.
  • Add the Firebase SDK to your app by ensuring that your root-level build.gradle file contains the Maven repository for Google:
    ```groovy
    buildscript {
    dependencies {
    classpath 'com.google.gms:google-services:4.3.10'
    }
    }
    allprojects {
    repositories {
    google()
    }
    }
    ```
  • Apply the google-services plugin in your app-level build.gradle:
    ```groovy
    apply plugin: 'com.android.application'
    apply plugin: 'com.google.gms.google-services'
    ```
  • Add dependencies to your app-level build.gradle file:
    ```groovy
    dependencies {
    // Firebase Cloud Messaging
    implementation 'com.google.firebase:firebase-messaging:23.0.0'
    }
    ```
  1. For iOS:
  • Register your app by entering the iOS bundle ID.

  • Download the GoogleService-Info.plist file and add it to your Xcode project.

  • Use CocoaPods to install Firebase in your project:
    ```
    pod 'Firebase/Messaging'
    ```

  • Initialize Firebase in your App Delegate:
    ```swift
    import Firebase

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()
    return true
    }
    }
    ```

 

Step 3: Set Up FCM Server Environment

 

  1. Navigate to the Firebase Console, and go to the "Project Settings."

  2. Click on the "Cloud Messaging" tab.

  3. There, you will find the server key, which is necessary for sending messages.

  4. For server-side setup, you can use any language or platform that can make HTTP POST requests. Below is an example using Node.js:

    ```javascript
    const fetch = require('node-fetch');

    async function sendMessage() {
    const response = await fetch('https://fcm.googleapis.com/fcm/send', {
    method: 'POST',
    headers: {
    'Authorization': 'key=YOUR_SERVER_KEY',
    'Content-Type': 'application/json'
    },
    body: JSON.stringify({
    to: 'DEVICE_REGISTRATION_TOKEN',
    notification: {
    title: 'Hello!',
    body: 'This is a notification message.'
    }
    })
    });

    const data = await response.json();
    console.log(data);
    }

    sendMessage();
    ```

 

Step 4: Implement FCM in Your App

 

  1. For Android:
  • Implement a service to handle message delivery. Create a class that extends FirebaseMessagingService:
    ```java
    public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
    // Handle the message
    String message = remoteMessage.getNotification().getBody();
    }
    }
    ```
  1. For iOS:
  • Request permission to receive notifications:
    ```swift
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
    // Handle permissions
    }
    ```
  • Implement UNUserNotificationCenterDelegate to handle incoming notifications:
    ```swift
    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // Handle foreground notification
    completionHandler([.banner, .badge, .sound])
    }
    }
    ```

Now, your app is set up to receive messages from Firebase Cloud Messaging. You can test sending notifications from the Firebase Console to confirm everything is working correctly.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022