FCM on iOS - Messaging.SharedInstance.FcmToken empty when app first installs/runs

JamesLaveryJamesLavery GBBeta, University ✭✭✭✭✭

We're using Xamarin.Firebase.iOS.CloudMessaging to get Push Notifications.

It's working fine except for one quirk.

When the app is first installed, RegisteredForRemoteNotifications is called, but Messaging.SharedInstance.Fcmtoken is not set.

When the app subsequently runs, it is set.

We need the FCM token so that we can send it to our back-end server.

How can I get the FCM Token on first installation?

My code is:

    public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
    {
        // NOTE that the token passed in here is the Apple APNS token.
        // We need the Firebase FCM Token -  this is what is used to manage token sending in Firebase.

        Messaging.SharedInstance.ApnsToken = deviceToken;

        // Why is this empty the first time the app runs?
        var fcmToken = Messaging.SharedInstance.FcmToken;

        Debug.WriteLine($"RegisteredForRemoteNotifications token:'{deviceToken}'");

        // This method can be called with no FCM Token set - so only do something when we've got the token
        if (!string.IsNullOrEmpty(fcmToken))
        {
            Debug.WriteLine($"RegisteredForRemoteNotifications fcmtoken:'{Messaging.SharedInstance.FcmToken}'");

            // Subscribe to a 'news' topic so we can send to just those subscribed to this topic
            Messaging.SharedInstance.Subscribe("news");

            // TODO - we will need to send the fcmToken to the back-end server, with the user details, so that the back-end server
            // can then manage notifications and send targetted Notifications to the specific user (e.g. a warning that their policy is expiring soon).
            //SendPushNotificationTokenToTempcoverServer(fcmToken);
        }

    }

Best Answer

  • JamesLaveryJamesLavery GB ✭✭✭✭✭
    Accepted Answer

    The solution is to mark the AppDelegate class as an IMessagingDelegate. Once this is done, the DidReceiveRegistrationToken method is then called, instead of the RegisteredForRemoteNotifications method.

    This has the FCM token properly populated as the token argument.

Answers

  • JamesLaveryJamesLavery GBBeta, University ✭✭✭✭✭
    Accepted Answer

    The solution is to mark the AppDelegate class as an IMessagingDelegate. Once this is done, the DidReceiveRegistrationToken method is then called, instead of the RegisteredForRemoteNotifications method.

    This has the FCM token properly populated as the token argument.

Sign In or Register to comment.