/ Software Development

How to Setup Firebase Push Notification for iOS

Musaddique Billah Talha

Read more posts by this author.

Read More
How to Setup Firebase Push Notification for iOS

Push notification is a powerful way to boost user engagement and retention. It makes users getting more engage to your app. In this tutorial , we will learn how to configure your app to receive push notifications for iOS and to display them to your users using Firebase.

Make a Project with Firebase

  1. Go to Firebase and Sign in with your Google account.
  2. Create a New Project

Create a Project in Xcode

  1. Give a unique name as Bundle Identifier
  2. Go to Capabilites from Project and Turn Push Notification On

Add Cocoapods in Podfile

  1. open Podfile and include the following pods
pod 'Firebase/Core'
pod 'Firebase/Messaging'

  1. Open Terminal and go to the project folder. Then run the following code
pod install

Synchronize Project with Firebase

  1. Go to the Project and Copy Bundle Identifier
  2. Now go the the Firebase Console and click Add Firebase to your iOS app
  1. Paste the iOS bundle ID to that and click Add App. A file name GoogleService-info.plist will be downloaded and you have to add it to Project
  1. Click Continue > Finish in Firebase in browser and Finish it.

Generate Certificate Signing Request

  1. Now our goal is to produce the credentials that are going to enable us to contact our app from the Firebase Web Service. We can do this in two ways.
  2. By uploading APNs Authentication Key in Firebase (preferred way). In this process, you don’t have to upload production key differently. We will follow this.
  3. By uploading APNs Certificates for both development and production.
  4. Go to Firebase Console and select Project Settings > Cloud Messaging

Create Push Notification Certificate

  1. Go to Apple Developer Account from Here
  2. Go to Certificates, Identifiers & Profile. Select Keys > All from the left menu
  1. Click + button in the top right corner. Give key Name, check APNS enable and click continue. Then confirm it.
  1. You will see a page that tells you to Download the key. Download and Save it, cause it can’t be re-downloaded.
  1. Go to the Firebase Console and Upload the key file provided by Apple

By now we have established our credentials now with Firebase and with the Apple Push Notification Server on the Web Services. Now we have to update our code so that our application can correctly register with Apple Push Notification Services in order to receive messages from Firebase.

Configure Firebase

It's time to add some code into your project. Go to AppDelegate.swift file and import FirebaseMessaging and FirebaseCore.

import FirebaseCore
import FirebaseMessaging

Now copy the following function and call it from application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool in AppDelegate.swift file.

func setupFirebasePushNotifications(application: UIApplication, launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        
        if  UNUserNotificationCenter.self != nil {
            
            let authOptions: UNAuthorizationOptions = [.alert, .sound, .badge]
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (granted, error) in
                
                if error != nil {
                    print("UNUserNotificationCenter Error: \(error?.localizedDescription)")
                }
                else
                {
                    print("UNUserNotificationCenter No Error")
                    
                    DispatchQueue.main.async {
                        application.registerForRemoteNotifications()
                    }
                    
                    UNUserNotificationCenter.current().delegate = self
                }
            }
        }
        
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    }

Handling Device Token

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

Get FCM Token Using MessingDelegate Methods

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        
        print("DidReceiveRegistrationToken Remote Message FCM Token: \(fcmToken)")
}

Show Notification to User

Almost complete. It's time to show notification to the user. To do this you have to implement UNUserNotificationCenterDelegate methods

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        print("When App is in Foreground")
        
        let userInfo = notification.request.content.userInfo as? [String: Any]
        
        if UIApplication.shared.applicationState == UIApplication.State.inactive || UIApplication.shared.applicationState == UIApplication.State.background {
        
            //handle your notification info here
        }
        
        completionHandler(.alert)
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        print("When App is in Background")
        
        let userInfo = response.notification.request.content.userInfo as? [String: Any]
        
        //handle your notificaion info here
        
        // Print full message.
        print("Will Receive Notification:\(userInfo!)")
        
        completionHandler()
    }
}

That's it. Your project is now ready to send push notification to your user. You can also check our article on the Firebase Crashlytics and Performance Monitoring integration for Android.

Comment bellow if you have any question regarding this topic.

Happy coding 😊