Push Notifications with Firebase Cloud Messaging – Cheat Sheet

Add Required Libraries to Xcode Project with Cocoapods

pod 'Firebase/Core'  
pod 'Firebase/Messaging'

 Enable Push Notifications in Capabilities Tab

Enable Background Modes in Capabilities Tab

Note: Additionally to enabling the Background Modes, you also need to enable the Remote notifications mode by checking its checkbox as shown in the image below.

AppDelegate.swift – Libraries to Import

import Firebase
import UserNotifications

 AppDelegate.swift – Protocols to Add

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate 
{
}

AppDelegate.swift – Methods

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (isSuccess, error) in
            if let error = error {
                print(error.localizedDescription)
            }
        })
        
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }
    
    FirebaseApp.configure()
    application.registerForRemoteNotifications()

    return true
}

Called when Registration for Remote Notifications is successful

// Called when Registration is successfull
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        if let instanceIdToken = InstanceID.instanceID().token() {
            print("New token \(instanceIdToken)")
            sharedData["instanceIdToken"] = instanceIdToken
        }
    }

Called when Registration for Remote Notifications Fails

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Registration failed!")
}

Called when Cloud Message Arrives While App is in Foreground

// Firebase notification received
   @available(iOS 10.0, *)
   func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
       
       // custom code to handle push while app is in the foreground
       print("Handle push from foreground \(notification.request.content.userInfo)")
       
  
       // Reading message body
       let dict = notification.request.content.userInfo["aps"] as! NSDictionary
       
       var messageBody:String?
       var messageTitle:String = "Alert"
       
       if let alertDict = dict["alert"] as? Dictionary<String, String> {
           messageBody = alertDict["body"]!
           if alertDict["title"] != nil { messageTitle  = alertDict["title"]! }
           
       } else {
           messageBody = dict["alert"] as? String
       }
       
       print("Message body is \(messageBody!) ")
       print("Message messageTitle is \(messageTitle) ")

       // Let iOS to display message
       completionHandler([.alert,.sound, .badge])
   }

Called When Cloud Message is Received While App is in Background or is Closed

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
 
    print("Message \(response.notification.request.content.userInfo)")
 
    completionHandler()
}

Called When Silent Push Notification Arrives 

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        print("Entire message \(userInfo)")
        
        let state : UIApplicationState = application.applicationState
        switch state {
        case UIApplicationState.active:
            print("If needed notify user about the message")
        default:
            print("Run code to download content")
        }
        
        completionHandler(UIBackgroundFetchResult.newData)
    }

Called When Firebase Cloud Messaging Token is Refreshed 

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    print("Token refreshed")
}

 Read Badge Count and Decrease Badge Count By 1

func updateBadgeCount()
{
    var badgeCount = UIApplication.shared.applicationIconBadgeNumber
    if badgeCount > 0
    {
        badgeCount = badgeCount-1
    }
    
    UIApplication.shared.applicationIconBadgeNumber = badgeCount
}

Silent Push Notification Payload

{
 "content_available":true,
 "priority":"high",
 "data": {
  "articleId":"1234"
 },
 "to":" Device Token should be provided here"
}

Send Silent Push Message Using CURL

curl -X POST --header "Authorization: key= authorization key which you copy from Firebse app" \
   --header "Content-Type: application/json" \
   https://fcm.googleapis.com/fcm/send \
   -d "{\"to\":\" Device token comes here \",\"aps\":{\"content-available\":1}}"

 

Firebase for iOS – Video Courses