HomeiPhone UpdatesPush Notifications with Firebase Cloud Messaging - Cheat Sheet

Push Notifications with Firebase Cloud Messaging – Cheat Sheet


Add Required Libraries to Xcode Undertaking with Cocoapods

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

 Allow Push Notifications in Capabilities Tab

Allow Background Modes in Capabilities Tab

Notice: Moreover to enabling the Background Modes, you additionally must allow the Distant notifications mode by checking its checkbox as proven within the picture beneath.

AppDelegate.swift – Libraries to Import

import Firebase
import UserNotifications

 AppDelegate.swift – Protocols to Add

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate 
{
}

AppDelegate.swift – Strategies

func utility(_ utility: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override level for personalisation after utility launch.
    if #accessible(iOS 10.0, *) {
        // For iOS 10 show notification (despatched through APNS)
        UNUserNotificationCenter.present().delegate = self
        
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.present().requestAuthorization(choices: authOptions, completionHandler: { (isSuccess, error) in
            if let error = error {
                print(error.localizedDescription)
            }
        })
        
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(varieties: [.alert, .badge, .sound], classes: nil)
        utility.registerUserNotificationSettings(settings)
    }
    
    FirebaseApp.configure()
    utility.registerForRemoteNotifications()

    return true
}

Referred to as when Registration for Distant Notifications is profitable

// Referred to as when Registration is successfull
    func utility(_ utility: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Information) {

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

Referred to as when Registration for Distant Notifications Fails

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

Referred to as when Cloud Message Arrives Whereas App is in Foreground

// Firebase notification obtained
   @accessible(iOS 10.0, *)
   func userNotificationCenter(_ middle: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ choices:   UNNotificationPresentationOptions) -> Void) {
       
       // customized code to deal with push whereas app is within the foreground
       print("Deal with push from foreground (notification.request.content material.userInfo)")
       
  
       // Studying message physique
       let dict = notification.request.content material.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 physique is (messageBody!) ")
       print("Message messageTitle is (messageTitle) ")

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

Referred to as When Cloud Message is Acquired Whereas App is in Background or is Closed

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

Referred to as When Silent Push Notification Arrives 

func utility(_ utility: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        print("Whole message (userInfo)")
        
        let state : UIApplicationState = utility.applicationState
        swap state {
        case UIApplicationState.lively:
            print("If wanted notify person in regards to the message")
        default:
            print("Run code to obtain content material")
        }
        
        completionHandler(UIBackgroundFetchResult.newData)
    }

Referred to as When Firebase Cloud Messaging Token is Refreshed 

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

 Learn Badge Depend and Lower Badge Depend 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,
 "precedence":"excessive",
 "knowledge": {
  "articleId":"1234"
 },
 "to":" System Token must be supplied right here"
}

Ship Silent Push Message Utilizing CURL

curl -X POST --header "Authorization: key= authorization key which you copy from Firebse app" 
   --header "Content material-Kind: utility/json" 
   https://fcm.googleapis.com/fcm/ship 
   -d "{"to":" System token comes right here ","aps":{"content-available":1}}"

 

Firebase for iOS – Video Programs

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments