Implementing Push Notifications in iOS and Android Using Firebase (Part-1)

Implementing Push Notifications in iOS and Android Using Firebase (Part-1)

Push notifications are a powerful way to engage users by delivering timely updates, even when your app is not active.

Firebase Cloud Messaging (FCM) provides a robust, cross-platform solution for sending push notifications to iOS and Android devices. This guide walks you through the complete process of setting up and implementing push notifications using Firebase, covering both platforms in a concise yet detailed manner.


1. What are Push Notifications?

Push notifications are short, timely messages sent to users device to engage them with the app.

Firebase Cloud Messaging (FCM) is a free service by Google that allows developers to send notifications across platforms like Android, IOS, and Web.

2. How FCM Works: A Quick Overview

  • FCM Token: Each device registered with FCM gets a unique token. We can store the token in any database for future use. This token acts as the address for sending notifications to that device.
  • Server-to-FCM Communication: The server uses the FCM v1 HTTP API or Firebase Admin SDK to send messages to specific tokens.
  • FCM-to-Device Communication: Firebase delivers the notification to the device, which either displays it or processes it silently.

Article content



Prerequisites

Before starting, ensure you have:

  • A Firebase account (sign up at firebase.google.com).
  • An Apple Developer account ($99/year) with an Admin role for iOS push notifications (required to access keys and other items in the Apple Developer Portal).
  • Xcode (for iOS) and Android Studio (for Android) installed.
  • A physical iOS device for testing (simulators don’t support remote push notifications).
  • Basic knowledge of Swift (for iOS) and Kotlin/Java (for Android).

Set Up a Firebase Project

Article content

  • Create a Firebase Project:
  • Go to the Firebase Console.
  • Click “Add Project,” name your project, and enable Google Analytics (optional).


  • Add Apps to Your Project:
  • In the Firebase Console, click “Add App” for iOS and Android.
  • For iOS, enter your app’s Bundle ID (e.g., com.example.app).
  • For Android, enter your app’s Package Name (e.g., com.example.app).
  • Download the GoogleService-Info.plist (iOS) and google-services.json (Android) files.

Article content

Configure iOS for Push Notifications

Enable Push Notifications in Xcode

  1. Open your iOS project in Xcode.
  2. In the project navigator, select your target and go to “Signing & Capabilities.”
  3. Click “+ Capability” and add “Push Notifications.”

Article content

Set Up APNs in Apple Developer Portal

  1. Log in to your Apple Developer Account with an Admin role. Note: Only accounts with an Admin role can view and manage keys, certificates, and other items in the Apple Developer Portal. Non-admin roles may not see these options.
  2. Navigate to “Certificates, Identifiers & Profiles” > “Identifiers” and select your app’s Bundle ID.
  3. Enable “Push Notifications” under Capabilities.
  4. Go to “Keys” and create a new key with “Apple Push Notifications service (APNs)” enabled.
  5. Download the .p8 key file and note the Key ID and Team ID.

Article content
Article content


Article content

Upload APNs Key to Firebase

  1. In the Firebase Console, go to Project Settings > Cloud Messaging > iOS app configuration.
  2. Upload the .p8 key file, and enter the Key ID and Team ID.

Article content

Integrate Firebase SDK in iOS

  1. Install CocoaPods if not already installed: sudo gem install cocoapods.
  2. Create a Podfile in your project directory:

pod init        

3. Add the following to your Podfile:

pod 'Firebase/Messaging'        

4. Run pod install and open the .xcworkspace file.

5. Add the GoogleService-Info.plist file to your Xcode project.

6. Initialize Firebase in your AppDelegate.swift:

import Firebase
import FirebaseMessaging
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        UNUserNotificationCenter.current().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { granted, error in
            guard granted else { return }
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
            }
        }
        return true
    }
}

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        print("FCM Token: \(String(describing: fcmToken))")
        // TODO: Send token to your server for targeting notifications
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.banner, .sound, .badge])
    }
}        

7. If using SwiftUI, handle APNs token mapping manually:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
}        

Add Firebase SDK to Android

  1. Open your Android project in Android Studio.
  2. Place the google-services.json file in the app/ directory.
  3. In the project-level build.gradle, add:
  4. In the app-level build.gradle, add:
  5. Sync the project with Gradle.

buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.4.2'
    }
}
        

apply plugin: 'com.google.gms.google-services'
dependencies {
    implementation 'com.google.firebase:firebase-messaging:24.0.3'
}        

Update AndroidManifest.xml

  1. Add the following to AndroidManifest.xml between </application> and </manifest>:
  2. Add a service for handling FCM messages:

<uses-permission android:name="android.permission.INTERNET" />        
<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>        



Implement Firebase Messaging Service

Create a MyFirebaseMessagingService.kt file:

class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        remoteMessage.notification?.let {
            sendNotification(it.title, it.body)
        }
    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        // TODO: Send token to your server
        println("FCM Token: $token")
    }

    private fun sendNotification(title: String?, message: String?) {
        val channelId = "default_channel_id"
        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)

        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "Default Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            notificationManager.createNotificationChannel(channel)
        }

        notificationManager.notify(0, notificationBuilder.build())
    }
}        

Request Notification Permission (Android 13+)

ActivityCompat.requestPermissions(this,
        new String[]{Manifest.permission.POST_NOTIFICATIONS},
        101);        

Test Push Notifications

  • Run Your Apps:
  • For iOS, run the app on a physical device (not a simulator) and allow notifications when prompted.
  • For Android, run the app on a device or emulator.
  • Verify that the FCM token is printed in the console for both platforms.


  • Send a Test Notification:
  • In the Firebase Console, go to “Cloud Messaging” > “Create your first campaign.” Enter a title and message, select your app, and send the notification.

Article content


  • Verify Receipt:
  • Ensure the notification appears on your device’s lock screen or notification tray.
  • For iOS, check the console for the FCM token and notification receipt. For Android, verify the notification displays with the specified title and message.


Sending Targeted Notifications

  • Store FCM tokens in your backend server to send notifications to specific users.
  • Use the Firebase Admin SDK or HTTP v1 API to send notifications programmatically:

{
    "message": {
        "token": "FCM_TOKEN",
        "notification": {
            "title": "Test Notification",
            "body": "This is a test message!"
        }
    }
}        

Troubleshooting Tips

• iOS:

  • Ensure your Apple Developer Account has an Admin role to access keys and certificates.
  • Verify your Bundle ID matches in Xcode, Apple Developer Portal, and Firebase.
  • Confirm the APNs key is correctly uploaded.
  • Test on a physical device, as simulators don’t support push notifications.

p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px 'Helvetica Neue'} li.li1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px 'Helvetica Neue'} span.s1 {font: 9.0px Menlo} ul.ul1 {list-style-type: disc}

. Android:

  • Check that google-services.json is in the correct directory.
  • Ensure internet permissions are added in AndroidManifest.xml.
  • Confirm the device is connected to Google Play Services.


Conclusion

By following these steps, you can successfully implement push notifications for iOS and Android using Firebase Cloud Messaging. This setup enables you to engage users with timely updates, enhancing retention and interaction. For further customization, explore Firebase’s documentation or use libraries like Notifee for advanced notification features.


References


It is just an overview, what is push notification, how to integrate and what are the prerequisites.
In next part i will cover the in-depth concept and working of the whole system, how different services communicate together different use-cases etc, stay tuned !
Nikhil Goyal

Engineering Manager Bridging Business Goals with Technical Excellence

2mo

Aashish Gupta With FCM, developers can send two types of messages to users: notification messages and data messages.It will be great if you can put some insight on these two type of messages.

Shubham Bora

React.js Developer | 1.2 Years of Experience in Building Scalable Web Applications | Expertise in Frontend Development | Passionate About Delivering Clean and Efficient Code

2mo

Definitely worth reading

To view or add a comment, sign in

Others also viewed

Explore topics