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
Prerequisites
Before starting, ensure you have:
Set Up a Firebase Project
Configure iOS for Push Notifications
Enable Push Notifications in Xcode
Set Up APNs in Apple Developer Portal
Upload APNs Key to Firebase
Integrate Firebase SDK in iOS
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
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
<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
Sending Targeted Notifications
{
"message": {
"token": "FCM_TOKEN",
"notification": {
"title": "Test Notification",
"body": "This is a test message!"
}
}
}
Troubleshooting Tips
• iOS:
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:
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 !
Engineering Manager Bridging Business Goals with Technical Excellence
2moAashish 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.
React.js Developer | 1.2 Years of Experience in Building Scalable Web Applications | Expertise in Frontend Development | Passionate About Delivering Clean and Efficient Code
2moDefinitely worth reading