Search code examples
iosswiftfirebasefirebase-cloud-messagingfirebase-notifications

Push notifications in Swift iOS


I am working with iOS Swift Notifications Module. I'm not getting the Alert/Banner Notification on the device.

I’m able to get notification when the App is open i.e. in Foreground, but not when app in in Background or Terminated.

Following is my code

import UIKit

import UserNotifications

import Firebase

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

    var window: UIWindow?

    //  MARK: - Application Life Cycle
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        FIRApp.configure()

        askNotificationPermission(application)

        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.getFirebaseInstaceID(_:)), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)

        connectToFcm()

        return true
    }

    // MARK:- Push Notification Delegate Methods
    @nonobjc func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error)
    }

    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        let appdata = remoteMessage.appData as NSDictionary as! [String: AnyObject]
        print(appdata)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        print(userInfo)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
    }

    // Receive displayed notifications for iOS 10 devices.
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo
        print("Message ID: \(userInfo["gcm.message_id"]!)")
        print("%@", userInfo)
    }

    //  MARK: - Permissions
    func askNotificationPermission(_ application: UIApplication) {
        if #available(iOS 10.0, *) {

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (finished, error) in

            })

            UNUserNotificationCenter.current().delegate = self

            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {

            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
    }

    //  MARK: - Firebase Connection Methods
    @objc func getFirebaseInstaceID(_ notification: Notification) {

        if isNotNull(FIRInstanceID.instanceID().token() as AnyObject?) {
            let strFirebaseInstanceID = FIRInstanceID.instanceID().token()! as String
            if !strFirebaseInstanceID.isEmpty {
                print("Firebase Instance ID - \(strFirebaseInstanceID)")
                setString(strValue: strFirebaseInstanceID, forKey: Default.firebaseInstanceID)

                NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.nSendFirebaseID), object: nil)
            } else {
                setString(strValue: "", forKey: Default.firebaseInstanceID)
            }
        } else {
            setString(strValue: "", forKey: Default.firebaseInstanceID)
        }

        connectToFcm()
    }

    func connectToFcm() {
        FIRMessaging.messaging().connect { (error) in
            if (error != nil) {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
}

Solution

  • I forgot to add this method

    didReceiveRemoteNotification