Thursday, November 24, 2022
HomeTechnologyIntegrate push notification using Firebase messaging in swift – iOS swift tutorial...

Integrate push notification using Firebase messaging in swift – iOS swift tutorial – iOSTutorialJunction


Things required to integrate Push notification

Before we jump on to integrate push notification using Firebase messaging in iOS swift, you need few things at your disposal to test iOS push notification. Below is the list of things required to integrate and check push notification integration in iOS.

  • iPhone device – Push notification did not work on simulator
  • Apple developer account – Apple developer account is needed in order to run app on iPhone device and setting up Auth key or certificates on firebase app console.
  • App on Firebase.(You can use your gmail account to create an app on Firebase )

Setting up app

First open up Xcode and create a basic project(if you are using an existing project then open it up). First step is to turn on push notification capabilities for our app. Follow below steps to turn on push notification capability in your iOS app.

Steps to turn on push capability
  1. Select your project name. See picture for reference
  2. Select your app target. Select Signing and capabilities.
  3. Click on + Capability.
  4. Search for Push notification and click on searched result showing Push Notification.

Creating app on Firebase

  • Open https://firebase.google.com , and click on Go to console or Sign in.
  • Once you reached your Firebase console. Click on Add Project.
  • Enter your project name. Click Continue.
  • Analytics is recommended. But it’s your choice. For this tutorial, i made oi disabled.
  • Click Create Project. After few seconds Firebase project is created and you will get message “Your new project is ready,”. Click on continue.
  • Click on iOS icon to start procedure of adding Firebase to your iOS app.

Adding Firebase to iOS app

Copy bundle identifier from xcode project(Shown in below picture), and add it to Firebase app bundle if textbox.

Where to find bundle id in xcode project

You can give nick name to your app on Firebase and can add app store id for the app (if added to apple connect). Both of these steps are optional. Next we need to download .plist file provided by Firebase and add that .plist named as “GoogleService-Info.plist” to your project. Lastly we need to add Firebase libraries to our xcode project. We will going to use cocoapods for our xcode project.

You can find list of firebase pods from this link https://firebase.google.com/docs/ios/setup?authuser=0

Installing Firebase messaging pod

For this tutorial, we are only interested in Firebase messaging pod. Since we are only integrating push notification with Firebase in IOS.

  • Open terminal and type command
  • cd “path root directory of your project (where .xcodeproj file is located)” Tip:- Simply click on any file in your xcode project and click show in finder
  • pod init
  • open -e podfile
  • Once podfile is opened in TextEdit paste below line to it, Save file and go t o terminal window
  • pod install
  • After successful installation close your existing xcode project and reopen it with double tap on file name having extension .xcworkspace

Open AppDelegate.swift and add below code

import UIKit
import FirebaseCore
import FirebaseMessaging

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure() 
        return true
    }

Above code will initialize our Firebase object.

Requesting user permission for Push notification

Next step is to request permissions from user for the push notification. Add below code to your application: didFinishLaunchingWithOptions method.

import UIKit
import FirebaseCore
import FirebaseMessaging

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        FirebaseApp.configure()
        
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .sound,.badge]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { success, error in
            if error != nil {
                //we are ready to go
            }
        }
        application.registerForRemoteNotifications()
        
        return true
    }

In above code, we use UserNotificationCentre to request user to allow push notification having permissions for alert, sound and badge.

Conforming to UNUserNotificationCenterDelegate protocol

We need to implement delegates required for Push notification. First we will implement delegate that will give us device token. If you want to know basic mechanism behind how push notification works in apple ecosystem then please check below link

https://stackoverflow.com/questions/17262511/how-do-ios-push-notifications-work

Getting device token

extension AppDelegate: UNUserNotificationCenterDelegate {
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }
  
  	func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register with push")
    }
}

Delegate named didRegisterForRemoteNotificationsWithDeviceToken, gives us unique token for the device which wants to receive apple push notification. We will set this token to Firebase messaging apnsToken. You can send this apns token to your server if your server is sending notifications to you. Second delegate, named didFailToRegisterForRemoteNotificationsWithError will gets called if we fail to get device token.

Note:- Since Firebase by default use method swizzling, so we need to turn it off if we want to get push as we are mapping device token in IOS didRegisterForRemoteNotificationsWithDeviceToken delegate and not using Firebase token handler. We can disable method swizzling, by setting a key in info.plist file of our xcode project. Check below image.

Turning off Firebase method swizzling

Adding UNUserNotificationCenterDelegate

UNUserNotificationCenterDelegate has two delegates that we need to implement

  • willPresent notification :- This delegate will gets called once we receive push notification and our app is in foreground.
  • didReceive response:- This delegate will gets called when user clicks on notification.
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("Will gets called when app is in forground and we want to show banner")

        completionHandler([.alert, .sound, .badge])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("Will gets called when user tap on notifictaion")
        completionHandler()
    }
}

Creating Auth key

Open https://developer.apple.com/account/ and select Certificates, identifiers and profiles option. On left menu click on auth key option. Create it and download it to safe place as we need this key file in next step, all steps are self explanatory. Once your authkey is generated by apple, copy “Key ID”. Lastly, we required team id you can find your Team ID in the Apple Member Center under the membership tab

Adding Auth key to Firebase project

Lastly we need to add auth key or push certificates to Firebase project. Go to your Firebase project, and click on gear icon on top left corner. Select “Project Settings” -> “Cloud Messaging” -> Scroll down to IOS app and click on “Upload” button under “APNs Authentication Key” section. Upload auth key file created in last section, and key ID with team ID in required fields. Click upload.

Test Push notification

Run your app from xcode to real iPhone device. Allow push notification and send app to background. Now, open up Firebase project and find “Cloud Messaging” from left menu. Click on it. If this your first message you will see button having text “Send you first message”. Fill in the required form .Click Review, a pop up will show up on your screen. Click Publish. Your device will receive a push notification.

Where to go from here

In this tutorial, we learned how to integrate push notification in iOS app using Firebase cloud messaging in swift. We covered all steps from start to end where we received a push notification from Firebase. If you are looking for video tutorial for same then visit below link
https://youtu.be/Tjg5X30XhMw

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments