2

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 ?

Aravind A R
  • 2,674
  • 1
  • 15
  • 25
Anushka Madushan
  • 681
  • 2
  • 12
  • 31
  • can you please add a breakpoint on your didRecieveNotiofication & test it? – Gagan_iOS Jun 05 '17 at 06:35
  • @Gagan_iOS ya i added a break point but when app is in background it hits and when app is in foreground(App is open) it doesn't hit the break point. – Anushka Madushan Jun 05 '17 at 06:39
  • look at this link https://stackoverflow.com/questions/37232849/didreceiveremotenotification-is-not-running-when-app-is-running-foreground same problem – Gagan_iOS Jun 05 '17 at 06:44
  • Possible duplicate of [didReceiveRemoteNotification is not running when app is running (FOREGROUND)](https://stackoverflow.com/questions/37232849/didreceiveremotenotification-is-not-running-when-app-is-running-foreground) – gm_ Jun 11 '17 at 15:56
  • I think this is because it is a local Notification not a push when the app is open. It is sent through Firebase's FCM service not the Push Notification service I had to make a method implementing the `FIRMessagingDelegate` To get it to work extension PushManager: FIRMessagingDelegate { func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { updateMessageViewsAndBadges() } } – Dan Leonard Sep 29 '17 at 19:30

1 Answers1

0

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.

Subramani
  • 477
  • 2
  • 14