Firebase Push notification integration in swift

Add pod file in your projects

pod 'Firebase'
pod 'Firebase/Messaging'

Capabilities > on push notifications

Capabilities > on Background modes and select remote notifications

Capabilities > Add your app in firebase console and upload APNS .p12 file in firebase console

in appdelegate file add following code

import UIKit
import Firebase
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate , MessagingDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()
        Messaging.messaging().delegate = self

        if let token = InstanceID.instanceID().token()
        {
            if(getUserDefaultValue("Token") != token)
            {
                setUserDefaultValues("Token", value: token)
            }
        }
        
        registerForPushNotifications(application: application)
        return true
    }
   //MARK:- Push Notification Handling Method [Firebase]
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
        setUserDefaultValues("Token", value: fcmToken)
        
        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    }
    
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        Messaging.messaging().apnsToken = messaging.apnsToken
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
      
        Messaging.messaging().appDidReceiveMessage(userInfo)
        print(userInfo)
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Unable to register for remote notifications: \(error.localizedDescription)")
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")
        Messaging.messaging().apnsToken = deviceToken
        
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        } 
        let token = tokenParts.joined()
        print("Device Token: \(token)")
    }
    
    //MARK:- Push Notification Handling Method
    
    func registerForPushNotifications(application: UIApplication) {
        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: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
                // Enable or disable features based on authorization.
            }
        } else {
            // Fallback on earlier versions
        }
        application.registerForRemoteNotifications()
    }
    
    func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        if notificationSettings.types != .none {
            application.registerForRemoteNotifications()
        }
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        print(notification.request.content.userInfo)
        let userinfo : [AnyHashable : Any] = notification.request.content.userInfo
        self.handlePushNotificationForActiveState(userInfo: userinfo)
        
        completionHandler([.alert, .sound])
    }
    
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print(remoteMessage)
        UserDefaults.standard.set(true, forKey: "NOTIFICATION")
        UserDefaults.standard.synchronize()
        NotificationCenter.default.post(name: Notification.Name("pushnotification"), object: nil)   
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print(response)
        UserDefaults.standard.set(true, forKey: "NOTIFICATION")
        UserDefaults.standard.synchronize()
        NotificationCenter.default.post(name: Notification.Name("pushnotification"), object: nil)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo.description)
        
        if(application.applicationState == .active) {
            print("=====> Active State")
        }else if(application.applicationState == .background){
            print("=====> BackGround State") 
        }else if(application.applicationState == .inactive){
            print("=====> InActive State")
        }
        handlePushNotificationForActiveState(userInfo: userInfo)
    }
    
    func handlePushNotificationForActiveState(userInfo: [AnyHashable : Any]) {  
        let notificationInfo = userInfo as NSDictionary
        print(notificationInfo)
    }
}