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

Viewed 40117

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!

15 Answers

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

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!

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

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()

For Flutter, just asking for permissions will work.

FirebaseMessaging.instance.requestPermission();

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! :)

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

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

    <key>FirebaseAppDelegateProxyEnabled</key>
    <false/>
let token = await firebase.messaging().getToken();
await firebase.messaging().ios.registerForRemoteNotifications();

Solved my problem

Short answer, restarted my computer and it worked again.

I had the same error when upgrading react-native 0.59.9 to 0.61.2.

I created a new project from scratch using react-native init and then modified it to include the native config I had made. Finally I copied the files over to the directory where I had the original project, and worked out the changes and conflicts that needed.

Push notifications just stopped working on iOS even though I could see there were no modifications to the native iOS code that would cause this.

I deleted node_modules, ios/build and ios/Pods, restarted my machine, and then reinstalled all dependencies and notifications worked again.

I'm not sure why, but sharing still in case anyone else comes across the same error.

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();
    

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

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

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.

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."

Related