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

22

60

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!

Meritorious answered 5/10, 2019 at 8:27 Comment(0)
M
6

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

Meritorious answered 5/10, 2019 at 9:30 Comment(0)
M
60

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

Link to create a p8 key https://mcmap.net/q/330157/-ios-swift-how-to-create-p8-file

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!

Maines answered 24/9, 2021 at 14:10 Comment(6)
For my case, I missed the Background Modes Thanks!Pinnatipartite
I had everything in place except for the Background Modes. Thanks very much @You LoveSporocarp
It didn't work in my case.Ribband
more at firebase.flutter.dev/docs/messaging/apple-integrationDiscolor
Incredible. Thank you. Just trying to grasp why this is not in the official docs!Trillion
As I know, Background Modes are not needed for basic Push Notifications. However, in my case, adding Background Modes and then removing them works. Strange!Marceau
B
31

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

Broderick answered 17/2, 2022 at 18:0 Comment(6)
This fixes it. It's either a bug with their swizzling or just bad documentation from firebase.Bowsprit
where did you put this?Sig
Saved my day! Must be some sort of bugBasaltware
No f*ing way! This worked. I can go sleep at last! Thanks so much.Amadeo
For me it was the absence of this delegate function. I added it with just a print in it and it started working. See my answer about this swizzling issue.Sylviasylviculture
Amazing ! I was missing application.registerForRemoteNotifications() , thank you !Mode
E
24

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

Erleena answered 24/11, 2021 at 10:39 Comment(1)
Yes! I couldn't figure out why this wasn't working after I followed instructions carefully. Works fine on a real device :)Stercoraceous
C
23

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

Craw answered 9/2, 2021 at 16:30 Comment(0)
S
18

For Flutter, just asking for permissions will work.

FirebaseMessaging.instance.requestPermission();
Sanctum answered 28/6, 2021 at 15:52 Comment(0)
S
9

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.

Sylviasylviculture answered 1/3, 2023 at 18:43 Comment(1)
This works. You must add either swizzling to plist or put the above functions to make it workDither
H
7

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
Hygrometry answered 22/7, 2022 at 3:39 Comment(0)
M
6

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

Meritorious answered 5/10, 2019 at 9:30 Comment(0)
P
5

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

    <key>FirebaseAppDelegateProxyEnabled</key>
    <false/>
Pintail answered 4/12, 2021 at 3:10 Comment(0)
A
5

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)
        }
    }
}
Adios answered 27/3, 2023 at 20:0 Comment(1)
for me was mainly this problem, I tried to call .token before setting apnsToken.... after I did this fix, issue dismissGreensand
R
3

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();
Romeoromeon answered 25/4, 2023 at 11:13 Comment(0)
B
3

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

Bouffe answered 28/8, 2023 at 13:1 Comment(1)
thanks for that link. is there any documentation or does anyone know why this is the case?Ombudsman
E
2

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

Excogitate answered 6/5, 2021 at 12:44 Comment(2)
can u share the code ?Gizzard
@A.Shukri FirebaseMessaging.instance.requestPermission();Laky
O
1
let token = await firebase.messaging().getToken();
await firebase.messaging().ios.registerForRemoteNotifications();

Solved my problem

Overplay answered 5/3, 2020 at 7:16 Comment(0)
A
1

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();
    
Amicable answered 1/9, 2021 at 7:1 Comment(0)
B
1

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

Bubaline answered 18/1, 2023 at 14:32 Comment(0)
F
0

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

Flak answered 23/12, 2021 at 11:15 Comment(0)
K
0

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

Kitchener answered 22/4, 2022 at 17:34 Comment(0)
R
0

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.

Respective answered 13/8, 2022 at 19:49 Comment(0)
C
0

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

Cranial answered 14/7, 2023 at 18:26 Comment(0)
H
0

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!

Hostetler answered 21/1 at 14:33 Comment(0)
S
0

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

Strega answered 9/4 at 13:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.