FCM iOS Push Notification cannot receive any notification
Asked Answered
T

5

9

I've currently working with notifications and I've not succeed to get any notification from the Firebase FCM.

The podfile configuration is:

target 'Project' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for Project
  pod 'Firebase/Core'
  pod 'Firebase/Messaging'
end

I've activated Push Notifications and Remote Notifications from the Background fetches and already read the another topic in stackoverflow which is currently similar, in here

I want to share my AppDelegate codes with you but firstly I have to say the documents of the Google for push notifications seems a bit confusing because there are so many overrided method in here and every tutorial has different way to accomplish to receive a notification.

I've imported these

import Firebase
import FirebaseInstanceID
import UserNotifications
import FirebaseMessaging

Then there is the delegations

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate{
...
}

Then here is the willFinishLaunchWithOptions method

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        FirebaseApp.configure()
        Messaging.messaging().delegate = self



        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
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)

        }

        application.registerForRemoteNotifications()


        return true
    }

And here is the Messaging delegate functions.

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("MEssage ->  \(remoteMessage.appData)")
    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
    }

That function was in the Firebase documentation for setting apns token.

func application(application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        Messaging.messaging().apnsToken = deviceToken as Data
    }

I've sent hundreds of notifications from the FCM' and it sent successfully on the server side but when i log the received message there is nothing to income data.

If you ask that why I implement configuration in willFinish function there was a note in the documentation like that.

        For devices running iOS 10 and above, you must assign the
     UNUserNotificationCenter's delegate property and FIRMessaging's 
delegate property. For example, in an iOS app, assign it in the 
applicationWillFinishLaunchingWithOptions: or 
applicationDidFinishLaunchingWithOptions: method of the app delegate.

I would appreciate that any help from you, because its hard to see what's wrong with it for now.

Tolentino answered 14/12, 2018 at 19:3 Comment(7)
Are you saying that no notification is received, or that a notification is received, but without data?Pterosaur
Thank you for interest, No notification is received cause of there is no log for receivedTolentino
There is a difference between a notification and a message. Messages are data-based. Notifications appear on screen. They only appear when the app is in the background or closed. They will not appear when the app is in the foreground.Pterosaur
Yeah, but I tried both way to see what are currently happening, even in foreground test, there is no written message.Tolentino
I've used NWPusher and it works well, I've getting the hashable notification data with using manual push, but I do not about any idea why its not working with FCM.Tolentino
The reason it's working "should" be that you are registering 'apnsToken' . Use ` Messaging.messaging().fcmToken` and use that token to send the notification from FCMChelyuskin
@AakashDave thanks for reply, it works well now. I will read the documentation again.Tolentino
K
12
  1. Please check if you have activated Push Notifications in your Project Capabilities

  2. Create Development APNs certificate and add it to Firebase Console Project Settings

  3. In your App Delegate

    import FirebaseMessaging
    import UserNotifications
    
    
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate, 
    UNUserNotificationCenterDelegate, MessagingDelegate {
    
    var window: UIWindow?
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
         // Override point for customization after application launch.
    
    
    
        //REMOTE NOTIFICATION
    
        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)
        }
    
        application.registerForRemoteNotifications()
    
        Messaging.messaging().delegate = self
    
        let token = Messaging.messaging().fcmToken
        print("FCM token: \(token ?? "")")
    
    
        //Added Code to display notification when app is in Foreground
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
        } else {
            // Fallback on earlier versions
        }
    
    
        return true
    }
    
    
    func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken as Data
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        // Print full message.
        print(userInfo)
    
    }
    
    // This method will be called when app received push notifications in foreground
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    { completionHandler([UNNotificationPresentationOptions.alert,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.badge])
    }
    
    
    // MARK:- Messaging Delegates
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        InstanceID.instanceID().instanceID { (result, error) in
            if let error = error {
                print("Error fetching remote instange ID: \(error)")
            } else if let result = result {
                print("Remote instance ID token: \(result.token)")
            }
        }
    }
    
    
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("received remote notification")
    }
    
    
    
    }
    
Kristianson answered 16/12, 2018 at 3:33 Comment(0)
L
7

I'm using FirebaseMessaging v4.1.4 and have enabled method swizzling

application.registerForRemoteNotifications() --> First

Messaging.messaging().delegate = self --> Second

You have to set messaging delegate after requesting for remote notification. (I noticed that you're calling it before requesting for permission)

In my case because I called it before I did not receive APNS Token in didRegisterForRemoteNotificationsWithDeviceToken method for iOS 13 whereas firebase token was generated.

Maybe because the APNS was not generated and firebase was not mapped with the APNS Token you might have not received any notification.

Lemuellemuela answered 19/9, 2019 at 1:44 Comment(3)
i have the same issue, didRegisterForRemoteNotificationsWithDeviceToken not called in ios13. but its working fine in ios12. If you solved this problem please share the codeMaria
The above mentioned fix was what I did to solve the issue for iOS 13. Can you get the APNS token as well as the firebase token in didRegisterForRemoteNotificationsWithDeviceToken method?Lemuellemuela
My issue is solved. It was a network connection issueMaria
S
2

They say Caution: To use the FCM direct channel this way, you must send messages using the legacy HTTP API. The HTTP v1 API uses APNs for all messages sent to iOS devices. And you need to put Messaging.messaging().shouldEstablishDirectChannek = true

Strand answered 18/12, 2018 at 11:44 Comment(0)
M
2

I have the same issue on ios 13 devices. But it was working fine on below ios 13 devices. The issue was didRegisterForRemoteNotificationsWithDeviceToken method was not getting called on ios 13 device. After some research i found that it is due to network connection problem. Then i switched from my office wifi to cellular network, after that it worked. didRegisterForRemoteNotificationsWithDeviceToken returned device token.

Maria answered 19/10, 2019 at 9:20 Comment(1)
I turned cellular off and on then it works! Thank you!Braasch
B
0

I answered a similar question here.

A crucial step is enabling "Push Notification" in Capabilities.

Happy coding everyone!

Bequest answered 31/3, 2021 at 0:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.