Anushka Madushan
Anushka Madushan

Reputation: 681

Not receiving Firebase push notifications when app is open?

I'm using google firebase with iOS swift for push notification. I'm receiving notifications while app is open in back ground or phone is locked. But when app is open not receiving any notifications. Following is my AppDelegate. Any help would be appreciate?

import UIKit
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?


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

        //FIREBASE CONFIGS
        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 })
            // For iOS 10 data message (sent via FCM

            //Messaging.messaging().remoteMessageDelegate = self as! MessagingDelegate

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

        application.registerForRemoteNotifications()

        FirebaseApp.configure()
        //FIREBASE CONFIGS

        let alert = UIAlertController(title: "Test", message:"Message", preferredStyle: UIAlertControllerStyle.alert)

        // add an action (button)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

        // show the alert
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)

        return true
    }
    //For FIREBASE
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {

        if let messageID = userInfo["gcm_message_id"] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)

        let alert = UIAlertController(title: "FireBase", message:"didReceiveRemoteNotification", preferredStyle: UIAlertControllerStyle.alert)

        // add an action (button)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

        // show the alert
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)
    }

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

        if let messageID = userInfo["gcm_message_id"] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)


        let alert = UIAlertController(title: "FireBase", message:"didReceiveRemoteNotification fetchCompletionHandler", preferredStyle: UIAlertControllerStyle.alert)

        // add an action (button)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

        // show the alert
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)


        completionHandler(UIBackgroundFetchResult.newData)
    }
    func application(received remoteMessage: MessagingRemoteMessage) {
        print(" APNSData \(remoteMessage.appData)")
    }

    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
    }
    private func application(application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        Messaging.messaging().apnsToken = deviceToken as Data
    }




}

Please help me to figure out what went wrong ?

Upvotes: 2

Views: 4074

Answers (1)

Subramani
Subramani

Reputation: 477

Just add UNNotificationPresentationOptions in completion handler function,

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
    
        // Print full message.
        print(userInfo)
    
        // Change this to your preferred presentation option
       //It will help to get notification when app is active
        completionHandler([.alert, .badge, .sound])
    }

Note: I know this is years ago post but I'm just posting here for new users who struggling to solve this issue.

Upvotes: 0

Related Questions