invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.53k stars 2.19k forks source link

[🐛] The operation couldn’t be completed. No APNS token specified before fetching FCM Token #6893

Open k2xl opened 1 year ago

k2xl commented 1 year ago

Issue

Trying to get token from user.

import messaging from '@react-native-firebase/messaging';
import { registerRootComponent } from 'expo';
import React, { useEffect } from 'react';
import {
  Text
} from 'react-native';

async function onAppBootstrap() {
  // Register the device with FCM
  console.log('A');
  await messaging().registerDeviceForRemoteMessages();
  console.log('B');
  // Get the token
  const token = await messaging().getToken();

  // Save the token
  console.log('TOKEN ' + token);
}

function App() {
  useEffect(() => {
    onAppBootstrap();
  }, []);

  return (
    <Text>Hi</Text>
  );
}

console.log('Registering root component');
registerRootComponent(App);
export default App;

When running this on iOS simulator, I get A on the console but it never reaches B. On further debugging just calling await messaging() seems to do enough to hang.

I see now after adding initializeApp() with credentials from firebase the following error

The operation couldn’t be completed. No APNS token specified before fetching FCM Token

Project Files

Javascript

Click To Expand

#### `package.json`: ```json "@react-native-firebase/app": "^17.0.0", "@react-native-firebase/messaging": "^17.0.0", ``` #### `firebase.json` for react-native-firebase v6: ```json # N/A ```

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby # N/A ``` #### `AppDelegate.m`: ```objc // N/A ```


Android

Click To Expand

#### Have you converted to AndroidX? - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`: ```groovy // N/A ``` #### `android/app/build.gradle`: ```groovy // N/A ``` #### `android/settings.gradle`: ```groovy // N/A ``` #### `MainApplication.java`: ```java // N/A ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

System: OS: macOS 12.5 CPU: (10) arm64 Apple M1 Pro Memory: 227.88 MB / 16.00 GB Shell: 5.8.1 - /bin/zsh Binaries: Node: 19.5.0 - /opt/homebrew/bin/node Yarn: Not Found npm: 9.3.1 - /opt/homebrew/bin/npm Watchman: Not Found Managers: CocoaPods: 1.11.3 - /opt/homebrew/bin/pod SDKs: iOS SDK: Platforms: DriverKit 22.2, iOS 16.2, macOS 13.1, tvOS 16.1, watchOS 9.1 Android SDK: Not Found IDEs: Android Studio: 2022.1 AI-221.6008.13.2211.9477386 Xcode: 14.2/14C18 - /usr/bin/xcodebuild Languages: Java: 17.0.6 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: 18.1.0 => 18.1.0 react-native: 0.70.5 => 0.70.5 react-native-macos: Not Found npmGlobalPackages: *react-native*: Not Found ``` OUTPUT GOES HERE ``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [ ] Android - [x ] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `"@react-native-firebase/app": "^17.0.0", - "@react-native-firebase/messaging": "^17.0.0",` - **`Firebase` module(s) you're using that has the issue:** - `e.g. Instance ID` - **Are you using `TypeScript`?** - `Y`


SERCHAT commented 1 year ago

@giacomette this way runs on simulator. I have an other question now. I don't have a real device iphone 14 pro and i try to get a build for ios 14 pro on simulator then get this error. Now if i implement this code piece on production, iphone 14 pro devices can be get notifications from firebase ?

msouzadev commented 1 year ago

After updating to version 17.4.1, I'm getting the same error, in my case when I uninstall the app and install it again it works, but when I open the app again it returns the error. After downgrading to version 16.7.0 it worked normally

mikehardy commented 1 year ago

Stated differently, @msouzadev "After downgrading to version 16.7.0 I was able to continue using invalid FCM tokens that had no APNS token backing them, so my messages were undeliverable on those devices"

I believe my restatement is factually correct, and highlights the problem your app has. You'll need to figure why the APNS token is not being generated correctly for your app, or perhaps you'll need to wait longer for the async network process of APNS token generation to complete

github-actions[bot] commented 1 year ago

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

sandeep14 commented 1 year ago

After updating to version 17.4.3, I'm getting the same error, first new install giving token correctly but after killed app and opened app giving above issue.

Please help on this

hnvcam commented 1 year ago

For who still has this problem, please try to delete the key and the profile in the Apple developer, and then try to add again like the guidelines of Cloud Message. I suspect there are some mismatches between Firebase and APNs. I got the same message on the real device (ios: 15.7.3, rnfirebase: 17.5.0) even tried everything mentioned in this thread until I decided to recreate everything from Apple site and it works.

Jamal-ReachFirst commented 1 year ago

For who still has this problem, please try to delete the key and the profile in the Apple developer, and then try to add again like the guidelines of Cloud Message. I suspect there are some mismatches between Firebase and APNs. I got the same message on the real device (ios: 15.7.3, rnfirebase: 17.5.0) even tried everything mentioned in this thread until I decided to recreate everything from Apple site and it works.

Worked for me +1

sandeep14 commented 1 year ago

After updating to version 17.4.3, I'm getting the same error, first new install giving token correctly but after killed app and opened app giving above issue.

Please help on this

after calling in timeout of 2000 sec then we getting token for every time

Iamivan1996 commented 1 year ago

I get this error when update the app from Testflight, i am using Ver 17.3.2.

I found that when i install the previous app and get the fcmToken successfully . After that , i update the app from Testlight, then the getToken() function return this error.

DanielDanaee commented 1 year ago

I also tried getting the token in a setTimeout after 3000ms, seems to be reliable now. No clue why this would happen outside of Chrome V8 Engine as the server....

kg-currenxie commented 1 year ago

Same, getting it the first time (full app deletion and installation) works. Killing and restarting gets the error :|

📱(real device)

riku99 commented 1 year ago

I solved the problem by updating mac os and installing additional components of Xcode that were requested after the update.

thanksyouall commented 1 year ago

I removed my app from my device and built it again and it worked.

cunguyen-agilityio commented 1 year ago

Sometimes I got this, anyone here can share a solution?

kg-currenxie commented 1 year ago

After updating to version 17.4.3, I'm getting the same error, first new install giving token correctly but after killed app and opened app giving above issue.

Please help on this

@sandeep14 any luck for you?

sandeep14 commented 1 year ago

After updating to version 17.4.3, I'm getting the same error, first new install giving token correctly but after killed app and opened app giving above issue. Please help on this

@sandeep14 any luck for you?

after calling in timeout of 2000 sec then we getting token for every time

kg-currenxie commented 1 year ago

after calling in timeout of 2000 sec then we getting token for every time

Thx for your reply. Did not work for me tho :/

sjonchhe commented 1 year ago

Is there really no solution for this yet???

SubvertDev commented 12 months ago

I'm having similar issue in a Unity project, downgrading Firebase to 10.2.0 helped in my case. Maybe it's working in a later versions, but I didn't have enough time yet to check which ones are working too. Hope it helps someone!

faustoct1 commented 11 months ago

Any solution for this problem? Setup a project from scratch released on store, when it comes to push notification, i set the apns but nothing make it work. It's very trick.

Harikarthyk commented 11 months ago

I got that error after configuring the react-native-splash-screen, and before getting the token, I waited for 1000 ms, then it worked fine.

ashankaushalya97 commented 11 months ago

I got sorted it out by adding the <key>FirebaseAppDelegateProxyEnabled</key> <true /> property in info.plist file.

github-actions[bot] commented 10 months ago

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

glency-betterteem commented 10 months ago

if you are on iOS simulator, i just quit the simulator device and rerun again. I experienced the error when i tried to simulate notification via xcrun simctl push

skizzo commented 10 months ago

Could somebody please point me into a direction that explains what to enter as a parameter in await messaging().setAPNSToken('XXX');?

From what I understood, this is a required step in the latest version, but I can't find any info about how to obtain that value, calling getToken() always results in the error

[Error: [messaging/unregistered] You must be registered for remote messages before calling getToken, see messaging().registerDeviceForRemoteMessages().]
Pattygeek commented 10 months ago

I got sorted it out by adding the <key>FirebaseAppDelegateProxyEnabled</key> <true /> property in info.plist file.

this worked for me.

appa-gomi commented 9 months ago

It seems to me that getToken() doesn't get it right away after starting the app. You can get it after about 2-3 seconds. I first checked whether the APNsToken was set using getAPNsToken(), and then executed getToken() when the setting was complete. And you add the following to the getAPNsToken() Method in node_modules/@react-native-firebase/messaging/ios/RNFBMessaging/RNFBMessagingModule.m.

@@ -188,6 +188,7 @@ RCT_EXPORT_METHOD(getAPNSToken : (RCTPromiseResolveBlock)resolve : (RCTPromiseRe
                            }];
       return;
     }
+    resolve([NSNull null]);
   }
 }

If you do not do this, getAPNsToken() will not return on iOS.

chenweigh commented 9 months ago

same +1

//firebase.json
{
  "react-native": {
    "messaging_ios_auto_register_for_remote_messages": false
  }
}
//react-native code 
await messaging().registerDeviceForRemoteMessages()
const fcmToken = await messaging().getToken()

I nedd to getToken send to server.

when the key messaging_ios_auto_register_for_remote_messages is true, everything is ok.

react-native-firebase: 18.4.0
react-native: 0.72.3

I need this configuration key to turn notification on or off. Example switch button, turn on registerDeviceForRemoteMessages, turn off unregisterDeviceForRemoteMessages.

but when the key is true, the switch is false, and ture it on, I got warning Usage of "messaging().registerDeviceForRemoteMessages()" is not required. You only need to register if auto-registration is disabled in your 'firebase.json' configuration file via the 'messaging_ios_auto_register_for_remote_messages' property.

eggybot commented 9 months ago

question, base on some search I found that getting APNS token should be working on Simulator but I tried all settings and configuration on the documentation, it didn't work and still get the error/issue on the APNS Token.

Also, on the documentation in this link it says

Firebase Cloud Messaging integrates with the Apple Push Notification service (APNs), however APNs only works with real devices.

~Is Cloud Messaging allowed in Simulator or should I actually test on the real device?~

As there not clear answer, I switch to real devices and it all works

skizzo commented 9 months ago

Good point @eggybot, unfortunately the docs don't 100% clearly state whether it's even possible to get a messaging token on the iOS simulator:

Integrating the Cloud Messaging module on iOS devices requires additional setup before your devices receive messages.

It says "iOS devices", so I guess it's normal to get the "You must be registered for remote messages..." error on the iOS simulator. Would be cool to clarify this though, maybe the man @mikehardy himself could give us a hint about this? ;)

mikehardy commented 9 months ago

The iOS Simulator can get an APNs token and do messaging, if it is iOS 16+ and it is running on an Apple Silicon machine and macOS is 13+:

https://github.com/invertase/react-native-firebase/blob/main/CHANGELOG.md#features-11

Which leads to this chunk of diff:

https://github.com/invertase/react-native-firebase/commit/8d75b36f485af07ecfa653192ca56f761d0cc5b7#diff-348d828b3a27617f7b287d2f055dfe4641effd95bdf21cbfb87397c4675dea7fR22-R27

Where you can see the conditions that must be met and how I exercise this new (and pretty cool) feature as I implemented it for react-native-firebase v17 since I was eager to actually see this work and prove that it (and our implementation here) worked. It does!

In all other cases you need to make up a token and send it through setAPNSToken in order to try do anything with the FCM system, and you will not actually receive messages.

Sadly, I missed that chunk of documentation someone just linked, and I've posted PR #7381 to clarify it - I'll merge it shortly if no one has any comments but I'll leave it open for review in case anyone has a better of way of clarifying it, just post up a comment on the PR

Hope this helps

Rodney-Web commented 9 months ago

100% Fixed my issue by:

  1. setting FirebaseAppDelegateProxyEnabled to NO in Info.plist

  2. Go to AppDelegate.mm and add the following inside didFinishLaunchingWithOptions function: [application registerForRemoteNotifications];

  3. Go to didRegisterForRemoteNotificationsWithDeviceToken function and add this: [FIRMessaging messaging].APNSToken = deviceToken;

  4. Clean build and start build again.

(FYI, make sure to use real device for testing.)

Hope it works for you guys.

FYI: If you are using Firebase dynamic links for your project you can just switch the FirebaseAppDelegateProxyEnabled to YES as it causes issues with dynamic links.

dexiouz commented 9 months ago

3. didRegisterForRemoteNotificationsWithDeviceToken

Hi please where do I add or find this "didRegisterForRemoteNotificationsWithDeviceToken"

rhfksl commented 9 months ago
  1. didRegisterForRemoteNotificationsWithDeviceToken

Hi please where do I add or find this "didRegisterForRemoteNotificationsWithDeviceToken"

I setup "didRegisterForRemoteNotificationsWithDeviceToken" when I install @react-native-community/push-notification-ios

// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [FIRMessaging messaging].APNSToken = deviceToken;
 [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
samih-dev commented 9 months ago

Rodney-Web + rhfksl method worked for me, for those whom don't use @react-native-community/push-notification-ios, just comment OUT the code related: [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];

gerardcastell commented 8 months ago

For me, the key was in this sentence:

Getting an APNS token is an asynchronous network-bound process that could fail, or may even be disabled by some configuration issue. Adding a delay worked, nevertheless, I worked until a month ago. Do not know why this process takes much more time now. The code to make it work is the following:

const delay = ms => new Promise(res => setTimeout(res, ms));
await delay(1000);
return await messaging().getToken();

Thanks @mikehardy !

kg-currenxie commented 8 months ago

I'm curious why registerDeviceForRemoteMessages() promise won't give us back the tokens immediately? Most promises return a value/status etc..

Which apps would call registerDeviceForRemoteMessages but NOT get the tokens? Probably none 🤔 So let the library do that work instead..

Proposal:

registerDeviceForRemoteMessages.then(function({ fcmToken, apnsToken }) {
  console.log(fcmToken, apnsToken)
})

// or
const { fcmToken, apnsToken } = await registerDeviceForRemoteMessages()

This would eliminate all these issue with getToken/getAPNSToken.

mikehardy commented 8 months ago

It could hang indefinitely if network is down

ealimardaniii commented 7 months ago

You should first call getAPNSToken method and after that call setAPNSToken method

      await messaging().registerDeviceForRemoteMessages();
      const apnsToken = await messaging().getAPNSToken();
      if (apnsToken) {
        await messaging().setAPNSToken(apnsToken);
      }
     fcmToken = await messaging().getToken();
savio777 commented 7 months ago

I got sorted it out by adding the <key>FirebaseAppDelegateProxyEnabled</key> <true /> property in info.plist file.

this and

I fixed this by changing firebase.json

From

{
  "react-native": {
    "analytics_auto_collection_enabled": false,
    "messaging_auto_init_enabled": false,
    "messaging_ios_auto_register_for_remote_messages": false
  }
}

To

{
  "react-native": {
    "analytics_auto_collection_enabled": false,
    "messaging_auto_init_enabled": false,
    "messaging_ios_auto_register_for_remote_messages": true
  }
}

And deleted call

await messaging().registerDeviceForRemoteMessages()

work for me :) my configs:

    "react": "18.2.0",
    "react-native": "0.72.6",
    "@react-native-firebase/analytics": "^18.4.0",
    "@react-native-firebase/app": "^18.4.0",
    "@react-native-firebase/messaging": "^18.4.0",
mronline commented 7 months ago

I noticed something interesting. Could this be the cause of the problem?

While I was looking for an error I encountered on Android (onNotificationOpenedApp is not working on Android): I came across this comment by @mikehardy: https://github.com/crazycodeboy/react-native-splash-screen/issues/289#issuecomment-502406454

When I comment this line in AppDelegate.mm: [RNSplashScreen show];

The token comes, but if I remove the comment I get the error: "No APNS token specified before fetching FCM Token".

messaging().requestPermission().then(async (authorizationStatus) => {
    try {
        const fcmToken = await messaging().getToken();
        Alert.alert('fcmToken', fcmToken);
    } catch (e) {
        Alert.alert('fcmToken', e.message);
    }
});
mikehardy commented 7 months ago

That module is not recommended. No one should use it. I am shocked people still are.

React-native-bootsplash

mronline commented 7 months ago

After reading your comment, I immediately switched to React-native-bootsplash. Currently, I do not receive this error: "No APNS token specified before fetching FCM Token". Thank you.

mikehardy commented 7 months ago

@mronline another developer saved 😆 . Happy that helped

huydosgtech commented 6 months ago

I solved by adding this code into AppDelegate.mm file. You can try this solution. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [FIRMessaging messaging].APNSToken = deviceToken; //add this line }

hussainarthuna commented 5 months ago

I got the same error but after adding the below function it fixed my issue and now I can get the Token.

async registerAppWithFCM(): Promise<void> { await messaging().registerDeviceForRemoteMessages(); }

Maksim-creator commented 5 months ago

I got sorted it out by adding the <key>FirebaseAppDelegateProxyEnabled</key> <true /> property in info.plist file.

works for me

mohamedabkal commented 5 months ago

For me the issue was happening on ios because i didn't setup the Push Notifications capability correctly in App Store Connect. I followed this guide and it helped me a lot https://medium.com/@ashoniaa/react-native-expo-push-notifications-with-fcm-a-step-by-step-guide-fa5cfc0372fd

EduardoBravoP commented 4 months ago

After reading your comment, I immediately switched to React-native-bootsplash. Currently, I do not receive this error: "No APNS token specified before fetching FCM Token". Thank you.

This worked for me too, thank you!

DiegoDelBianco commented 4 months ago

I fixed this by changing firebase.json

From

{
  "react-native": {
    "analytics_auto_collection_enabled": false,
    "messaging_auto_init_enabled": false,
    "messaging_ios_auto_register_for_remote_messages": false
  }
}

To

{
  "react-native": {
    "analytics_auto_collection_enabled": false,
    "messaging_auto_init_enabled": false,
    "messaging_ios_auto_register_for_remote_messages": true
  }
}

And deleted call

await messaging().registerDeviceForRemoteMessages()

This solution work for me. Thanks.

I just create a firebase.json in root with the content:

{ "react-native": { "messaging_ios_auto_register_for_remote_messages": true } }

Then remove the line

await messaging().registerDeviceForRemoteMessages()