Prabash Darshana
Prabash Darshana

Reputation: 1115

APNS device token not set before retrieving FCM Token for Sender ID - React Native Firebase

I have been following this tutorial to set-up Remote Push notifications on my react-native application using react-native-firebase Version 5.2.0. After I configured everything and ran the application I get an error as:

APNS device token not set before retrieving FCM Token for Sender ID ''. Notifications to this FCM Token will not be delievered over APNS. Be sure to re-retrieve the FCM token once the APNS token is set.

Been trying to figure out how to solve this issue but wasn't quite successful. Running on react-native : 0.61.2, react-native-firebase: 5.2.0

Following is my AppDelegate.m

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <RNCPushNotificationIOS.h>
#import <UserNotifications/UserNotifications.h>
#import <Firebase.h>

@import Firebase;
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [FIRApp configure];
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"helloworld"
                                            initialProperties:nil];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

  // define UNUserNotificationCenter
  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  center.delegate = self;

  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
  [RNCPushNotificationIOS didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  [RNCPushNotificationIOS didReceiveLocalNotification:notification];
}

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  NSLog(@"User Info : %@",notification.request.content.userInfo);
  completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}


@end

and token retrieval on my App.js:

const messaging = firebase.messaging();

messaging.hasPermission()
  .then((enabled) => {
    if (enabled) {
      messaging.getToken()
        .then(token => { console.log("+++++ TOKEN ++++++" + token) })
        .catch(error => { console.log(" +++++ ERROR GT +++++ " + error) })
    } else {
      messaging.requestPermission()
        .then(() => { console.log("+++ PERMISSION REQUESTED +++++") })
        .catch(error => { console.log(" +++++ ERROR RP ++++ " + error) })
    }

  })
  .catch(error => { console.log(" +++++ ERROR +++++ " + error) });

Any help would be much appreciated! Thanks!

Upvotes: 63

Views: 114676

Answers (22)

Artem Iashkov
Artem Iashkov

Reputation: 21

Pushes worked before, so I restarted Simulator, rebuilt app and everything worked!

Upvotes: 2

VladislavSmolyanoy
VladislavSmolyanoy

Reputation: 528

After wasting my whole day trying to find a fix for this weird bug, I found a solution that fixed it for me. In my case, Cloud Messaging somehow screwed up the APN Token setup process, so I had to manually set it myself:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("Registered for Apple Remote Notifications")
    Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
}

Of course you have to register for remote notifications beforehand to even receive notifications via application.registerForRemoteNotifications()


Doc ref:

If you have disabled method swizzling, or you are building a SwiftUI app, you'll need to explicitly map your APNs token to the FCM registration token.

https://firebase.google.com/docs/cloud-messaging/ios/client?authuser=0#token-swizzle-disabled

Upvotes: 32

Otto Ranta-Ojala
Otto Ranta-Ojala

Reputation: 130

I ran into this issue while running my app on a simulator. There were no issues previously. Docs said that old software might be the issue so I updated my MacOS from 13.5 to 14.2 and iOS to 17.2. Token generation and push notifications started working again after that!

Upvotes: 0

Robert
Robert

Reputation: 241

If you're working with SwiftUI apps and Firebase 10.14.0 (as of August 2023) and facing issues related to APNs tokens and Firebase Cloud Messaging (FCM) registration tokens, here's a solution:

Even if you have NOT disabled swizzling, you'll need to explicitly map your APNs token to the FCM registration token. You can do this by adding the following code to your AppDelegate:

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

This solution is based on the official Firebase documentation which states:

"If you have disabled method swizzling, or you are building a SwiftUI app, you'll need to explicitly map your APNs token to the FCM registration token."

https://firebase.google.com/docs/cloud-messaging/ios/client#token-swizzle-disabled

Upvotes: 5

Quick learner
Quick learner

Reputation: 11457

For me i disabled Background app refresh option in my iphone 14 when i turned it on it worked well

enter image description here

enter image description here

Upvotes: 0

heyfrank
heyfrank

Reputation: 5647

In my case I it stopped working at some point. Later I found out, that it was because I removed those two functions from my AppDelegate

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("application didRegisterForRemoteNotificationsWithDeviceToken")
}

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

Firebase Messaging uses swizzling to replace those functions with its own implementation. But, if those functions are not there in your code, it seems that it can't get their code swizzled in.

Upvotes: 9

Fatih CEYLAN
Fatih CEYLAN

Reputation: 51

I tried everything but this error keep coming till I update AppDelegate.mm file and get APNS token awating as follows:

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken: (NSData *)deviceToken
    {
      [FIRMessaging messaging].APNSToken = deviceToken;
      NSString *fcmToken = [FIRMessaging messaging].FCMToken;
      NSLog(@"++APNS deviceToken : %@", deviceToken);
      NSLog(@"++FCM device token : %@", fcmToken);
    }
    
    -(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
    {
      NSLog(@"!!! ERROR regisgering for APNS : %@", error);
    }

Before getting token, get APNS token.

const apnsToken = await messaging().getAPNSToken();
var token = await messaging().getToken();

Upvotes: 3

jamal zare
jamal zare

Reputation: 1199

I resolved this issue easily on didRegisterForRemoteNotificationsWithDeviceToken method:

  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().apnsToken = deviceToken
    //FCM TOken
    Messaging.messaging().token { token, error in
        if let error = error {
            print("Error fetching FCM registration token: \(error)")
        } else if let token = token {
            print(token)
        }
    }
}

Upvotes: 5

Jesus Fortuna
Jesus Fortuna

Reputation: 164

What solved my issue was debugging this in a real device. Unfortunately, I forgot that notifications don't work on the simulator...

Upvotes: 1

Bash
Bash

Reputation: 155

I've had a similar issue after renaming the target folders Xcode and the Bundle ID. Tried many things as mentioned above. Recreating the certificates. Removing and adding the App in Firebase etc. Nothing worked. I ended up recreating a new project and copying over all assets and code. After 2 hours of work (not a very large app), it finally works.

Upvotes: 0

Ismael Barri
Ismael Barri

Reputation: 71

If anyone is 100% sure they did all the steps correctly like

  • adding the GoogleService-Info.plist to your project
  • adding Auth Key p8 to Firebase
  • Giving your app capabilities "Push Notifications" and "background Modes(Background fetch, Remote Notifications)"
  • Making sure your app Bundle Id matches the one added in firebase
  • Also i advice allowing Xcode to Automatically manage signing by checking the tick box in general tab "Automatically manage signing" and then selecting a team, when you do this Xcode will generate proper certificates and profiles for you no need to go to your developer account
  • your phone got internet connection

If you did all that and still not getting remote notifications and getting the error "APNS device token not set before retrieving FCM Token for Sender ID"

check your info.plist if you have this record "FirebaseAppDelegateProxyEnabled" set to "false"

    <key>FirebaseAppDelegateProxyEnabled</key>
    <false/>

Then you need to add the following code to your AppDelegate.m

    -(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken: (NSData *)deviceToken
    {
      [FIRMessaging messaging].APNSToken = deviceToken;
      NSString *fcmToken = [FIRMessaging messaging].FCMToken;
      NSLog(@"++APNST deviceToken : %@", deviceToken);
      NSLog(@"++FCM device token : %@", fcmToken);
    }

then

  • "pod install --repo-update"
  • "cmd + shift + k"
  • build and try

Upvotes: 7

aas
aas

Reputation: 37

I updated my POD . Latest Firebase SDK started getting used ( confirmed from Podfile.lock file) and in Xcode logs the following error disappeared. " APNS device token not set before retrieving FCM Token for Sender ID 'XXXXXXXXXXXXX'. Notifications to this FCM Token will not be delivered over APNS.Be sure to re-retrieve the FCM token once the APNS device token is set."

Upvotes: 0

landonandrey
landonandrey

Reputation: 1341

In my case I've just re-created APNs key on Apple Developer Portal, uploaded to Firebase Cloud Message and pushes started to work.

Upvotes: 0

maz
maz

Reputation: 8336

After adding this to Info.plist I finally got a push:

    <key>FirebaseAppDelegateProxyEnabled</key>
    <false/>

Upvotes: 5

Vladimir Sukanica
Vladimir Sukanica

Reputation: 575

Maybe someone had mentioned before... You must use real device, not simulator, or this error will show always.

Upvotes: 28

Artur
Artur

Reputation: 837

I solved this problem in 3 days. You need to connect the p8 key to your firebase

Link to create a p8 key https://stackoverflow.com/a/67533665/13033024

enter image description here

Add the following code to your AppDelegate.swift

 if #available(iOS 10.0, *) { 
     UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
    }
   
 application.registerForRemoteNotifications()

Go to xCode and click on the "Capability" tab. Add Background Modes and Push Notifications. In the Background Modes tab, enable Background fetch and Remote notifications

Don't forget to add it for release, debug, profile

enter image description here

Remove your app from your phone and run it again.

I hope this will help you too!

Upvotes: 62

CopsOnRoad
CopsOnRoad

Reputation: 267544

Flutter solution

  1. Enable Background Modes:

    enter image description here

  1. Request notification permission:

    FirebaseMessaging.instance.requestPermission();
    
  2. Get the Token ID (Optional)

    String? token = await FirebaseMessaging.instance.getToken();
    

Upvotes: 1

Sirsha Chakraborty
Sirsha Chakraborty

Reputation: 189

For Flutter, just asking for permissions will work.

FirebaseMessaging.instance.requestPermission();

Upvotes: 18

ndutra
ndutra

Reputation: 29

I'm using Flutter and in my case I'd forgotten to ask for permission to handle messaging.

Upvotes: 2

MilesStanfield
MilesStanfield

Reputation: 4639

For anyone else, this warning/error will also appear if you've forgotten to add the Push Notification capability in the Signing & Capabilities tab of your project target in Xcode

Upvotes: 24

Pavel Nikolaev
Pavel Nikolaev

Reputation: 109

let token = await firebase.messaging().getToken();
await firebase.messaging().ios.registerForRemoteNotifications();

Solved my problem

Upvotes: 1

Prabash Darshana
Prabash Darshana

Reputation: 1115

I was able to fix the issue: it was quite simple honestly. My iPhone has had an issue with connecting to the internet, and I fixed it and this issue got fixed too! :)

Upvotes: 7

Related Questions