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.66k stars 2.21k forks source link

🔥 messaging().getToken() always throws: "You must be registered for remote messages before calling getToken" on iOS #4788

Closed StefanoCremona closed 3 years ago

StefanoCremona commented 3 years ago

Hello, there. I migrated my project from v5 to v6 and I have a problem retrieving the messaging token just on iOS.

At the app startup I call this method:

firebase.messaging().registerDeviceForRemoteMessages()

in the firebase.json I have (I explain later why):

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

the code I'm executing is:

console.log(
    'myMethod: ',
    'isDeviceRegisteredForRemoteMessages', firebase.messaging().isDeviceRegisteredForRemoteMessages,
  )
  if (
    Platform.OS === 'ios' &&
    !firebase.messaging().isDeviceRegisteredForRemoteMessages
  ) {
    console.log('myMethod: ', 'registerDeviceForRemoteMessages')
    await firebase.messaging().registerDeviceForRemoteMessages()
  }

  try {
    console.log( 'myMethod: ', 'call get token')
    const pushToken = await firebase.messaging().getToken()
    console.log(
      'registerDeviceForRemoteMessages: ',
      'setErrorUser',
      'got token',
    )
    /* other code .... */
  } catch (error) {
    console.log('myMethod: ','Error after getToken: ', error)
  }

What I get in the log is:

2021-01-15 20:54:11.354 [info][tid:com.facebook.react.JavaScript] 'myMethod: ', 'isDeviceRegisteredForRemoteMessages', true
2021-01-15 20:54:11.355 [info][tid:com.facebook.react.JavaScript] 'myMethod: ', 'call get token'
2021-01-15 20:54:11.432 [info][tid:com.facebook.react.JavaScript] 'myMethod: ', 'Error after getToken: ', [Error: [messaging/unregistered] You must be registered for remote messages before calling getToken, see messaging().registerDeviceForRemoteMessages().]

Some notes, because I'm coming from different tests and errors. 1) WITHOUT the firebase.json The expected behaviour is that the app is registered automatically for messages. So I shouldn't register it manually. Despite of this I have isDeviceRegisteredForRemoteMessages: false and running getToken directly (without calling registerDeviceForRemoteMessages), I get anyway the error in the subject. If I put the try/catch to run registerDeviceForRemoteMessages, its promise is never resolved and the code is stuck with that call.

2) WITH the firebase.json and "messaging_ios_auto_register_for_remote_messages": true Exactly the same behaviour of the point 1. It doesn't matter where I put the firebase.json (root_project, ios dir, root/firebase). The app is not registered for notifications and getToken fails with the same error.

3) RNFBMessagingModule.m Debugging the native code I see that the the javascript constant isRegisteredForRemoteNotifications gets the value in this way: constants[@"isRegisteredForRemoteNotifications"] = @([RCTConvert BOOL:@([[UIApplication sharedApplication] isRegisteredForRemoteNotifications])]);

and the getToken check is: if ([UIApplication sharedApplication].isRegisteredForRemoteNotifications == NO) {...

So, if I change the getToken check into: if (@([RCTConvert BOOL:@([[UIApplication sharedApplication] isRegisteredForRemoteNotifications])]) == NO) {...

everything works fine and I get back my token.

Is there a bug?

Project Files

Javascript

Click To Expand

#### `package.json`: ```json { "name": "navico-track-app", "version": "0.1.0", "private": true, "devDependencies": { "@babel/core": "^7.6.2", "@babel/plugin-external-helpers": "^7.0.0", "@babel/runtime": "^7.6.2", "@react-native-community/eslint-config": "^0.0.5", "babel-eslint": "^8.2.2", "babel-jest": "^24.9.0", "babel-plugin-transform-remove-console": "^6.9.4", "babel-polyfill": "^6.26.0", "babel-preset-react-native-stage-0": "^1.0.1", "eslint": "^6.4.0", "eslint-config-airbnb": "^16.1.0", "eslint-plugin-import": "^2.9.0", "eslint-plugin-jsx-a11y": "^6.0.3", "eslint-plugin-react": "^7.7.0", "jest": "^24.9.0", "jest-react-native": "^18.0.0", "metro-react-native-babel-preset": "^0.56.0", "react-test-renderer": "16.8.6", "schedule": "0.4.0" }, "scripts": { "start": "react-native start", "android": "cd ./android && ./gradlew app:assembleDebug && ./gradlew installDebug", "detox": "detox build && detox test -l verbose", "ios": "react-native run-ios", "test": "node node_modules/jest/bin/jest.js", "lint": "eslint .", "build-ios-debug": "detox build -c ios.sim.debug -l verbose", "build-ios-release": "detox build -c ios.sim.release -l verbose", "run-ios-debug": "detox test -c ios.sim.debug -l verbose", "run-ios-release": "detox test -c ios.sim.release -l verbose", "build-android-debug": "detox build -c android.emu.debug -l verbose", "build-android-release": "detox build -c android.emu.release -l verbose", "run-android-debug": "detox test -c android.emu.debug -l verbose", "run-android-release": "detox test -c android.emu.release -l verbose", "purge": "cd node_modules/react-native/third-party/glog-0.3.5/ && ../../scripts/ios-configure-glog.sh && cd ../../../../ && rm -rf /tmp/metro-bundler-cache-* && rm -rf /tmp/haste-map-react-native-packager-* && yarn start -- --reset-cache", "postinstall": "npx jetify && cd ./scripts && bash fixAppAuthLogOut.sh && bash fixBlueAlertArea.sh" }, "jest": { "preset": "react-native", "cacheDirectory": "./cache", "transform": { "^.+\\.js$": "babel-jest" }, "coverageThreshold": { "global": { "statements": 80 } }, "transformIgnorePatterns": [ "/node_modules/(?!react-native|react-clone-referenced-element|react-navigation|react-native-navigation)" ] }, "dependencies": { "@dudigital/react-native-zoomable-view": "^1.0.12", "@react-native-community/async-storage": "^1.7.1", "@react-native-community/blur": "^3.3.1", "@react-native-community/netinfo": "^5.0.0", "@react-native-firebase/analytics": "^10.4.1", "@react-native-firebase/app": "^10.4.0", "@react-native-firebase/auth": "^10.4.1", "@react-native-firebase/crashlytics": "^10.4.1", "@react-native-firebase/firestore": "^10.4.1", "@react-native-firebase/messaging": "^10.4.1", "@sentry/react-native": "^1.0.6", "@turf/bbox": "^6.0.1", "@turf/circle": "^6.0.1", "@turf/length": "^6.0.2", "@turf/turf": "^5.1.6", "axios": "^0.18.0", "babel-preset-es2015": "^6.24.1", "babel-preset-react-native": "^4.0.1", "buffer": "^5.1.0", "convert-units": "^2.3.4", "fetch": "^1.1.0", "formatcoords": "^1.1.3", "haversine": "^1.1.0", "jetifier": "^1.6.5", "js-base64": "^2.4.5", "jwt-decode": "^2.2.0", "lodash": "^4.17.11", "moment": "^2.22.1", "moment-timezone": "^0.5.23", "node-fetch": "^2.1.1", "node-schedule": "^1.3.0", "pretty-format": "^22.4.3", "prop-types": "^15.6.2", "querystringify": "^2.1.1", "react": "16.8.6", "react-native": "0.60.6", "react-native-actionsheet": "^2.4.2", "react-native-android-open-settings": "^1.3.0", "react-native-animatable": "^1.3.0", "react-native-app-auth": "5.0.0-rc3", "react-native-appsflyer": "^1.4.7", "react-native-calendars": "^1.21.0", "react-native-camera": "^3.13.1", "react-native-code-push": "^5.7.0", "react-native-custom-actionsheet": "0.0.4", "react-native-device-info": "^5.3.1", "react-native-elements": "^0.19.1", "react-native-global-props": "^1.1.5", "react-native-google-analytics": "^1.3.2", "react-native-haptic": "^1.0.5", "react-native-hide-show-password-input": "^1.0.7", "react-native-hyperlink": "0.0.14", "react-native-iap": "^5.0.1", "react-native-image-gallery": "^2.1.5", "react-native-image-pan-zoom": "^2.1.11", "react-native-image-picker": "^0.27.1", "react-native-image-sequence": "^0.7.0", "react-native-iphone-x-helper": "^1.2.0", "react-native-keyboard-aware-scrollview": "^2.0.0", "react-native-keychain": "^4.0.2", "react-native-linear-gradient": "^2.4.0", "react-native-localization": "^2.1.0", "react-native-localize": "^1.3.1", "react-native-mail": "^3.0.7", "react-native-maps": "^0.26.1", "react-native-masked-text": "^1.9.2", "react-native-material-textfield": "^0.12.0", "react-native-modal": "^6.5.0", "react-native-modal-datetime-picker": "^5.1.0", "react-native-navigation": "^4.0.4", "react-native-onboarding-swiper": "^0.6.0", "react-native-permissions": "^3.0.0-beta.2", "react-native-qrcode-scanner": "^1.1.2", "react-native-remote-svg": "^1.2.0", "react-native-snackbar-component": "^1.1.0", "react-native-splash-screen": "^3.0.9", "react-native-super-grid": "^3.0.3", "react-native-svg": "^6.3.1", "react-native-svg-charts": "^4.2.0", "react-native-video": "^5.0.0", "react-native-webview": "^8.0.3", "react-native-xml2js": "^1.0.3", "react-redux": "^5.0.7", "redux": "^3.7.2", "redux-act": "^1.7.4", "redux-saga": "^0.16.0", "rn-sliding-up-panel": "2.1.1", "rn-viewpager": "^1.2.9", "sha256": "^0.2.0", "short-unique-id": "^1.1.1", "string-format": "^2.0.0", "time-greeting": "^1.0.1", "turf": "^3.0.14", "util": "^0.10.3" }, "detox": { "configurations": { "ios.sim.debug": { "binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/navicotrackapp.app", "build": "xcodebuild -workspace ios/navicotrackapp.xcworkspace -scheme navicotrackapp -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build", "type": "ios.simulator", "name": "iPhone 8" }, "ios.sim.release": { "binaryPath": "ios/build/Build/Products/Release-iphonesimulator/navicotrackapp.app", "build": "xcodebuild -workspace ios/navicotrackapp.xcworkspace -scheme navicotrackapp -configuration Release -sdk iphonesimulator -derivedDataPath ios/build", "type": "ios.simulator", "name": "iPhone 8" }, "android.emu.debug": { "binaryPath": "android/app/build/outputs/apk/debug/app-debug.apk", "build": "cd android && ./gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug && cd ..", "type": "android.emulator", "name": "Pixel_API_28" }, "android.emu.release": { "binaryPath": "android/app/build/outputs/apk/release/app-release.apk", "build": "cd android && ./gradlew assembleRelease assembleAndroidTest -DtestBuildType=release && cd ..", "type": "android.emulator", "name": "Pixel2" }, "android.attached.release": { "binaryPath": "android/app/build/outputs/apk/release/app-release.apk", "build": "cd android && ./gradlew assembleRelease assembleAndroidTest -DtestBuildType=release && cd ..", "type": "android.attached", "name": "ce031713ec43d02802" } }, "test-runner": "jest", "runner-config": "e2e/config.json" } } ``` #### `firebase.json` for react-native-firebase v6: ```json { "react-native": { "messaging_ios_auto_register_for_remote_messages": false } } ```

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ``` # Uncomment the next line to define a global platform for your project require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' target 'navicotrackapp' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks # use_frameworks! platform :ios, '12.0' # Override Firebase SDK Version $FirebaseSDKVersion = '7.0.0' # Pods for PodTest pod 'Fabric', '~> 1.10.2' pod 'Crashlytics', '~> 3.14.0' # pod 'react-native-splash-screen', :path => '../node_modules/react-native-splash-screen' rn_path = '../node_modules/react-native' rn_maps_path = '../node_modules/react-native-maps' # See http://facebook.github.io/react-native/docs/integration-with-existing-apps.html#configuring-cocoapods-dependencies pod 'React', :path => '../node_modules/react-native/' pod 'React-Core', :path => '../node_modules/react-native/React' pod 'React-DevSupport', :path => '../node_modules/react-native/React' pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS' pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation' pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob' pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image' pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS' pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network' pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings' pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text' pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration' pod 'React-RCTWebSocket', :path => '../node_modules/react-native/Libraries/WebSocket' pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact' pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi' pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor' pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector' pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga' pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec' pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec' pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec' # react-native-maps dependencies pod 'react-native-maps', path: rn_maps_path pod 'react-native-google-maps', path: rn_maps_path # Uncomment this line if you want to support GoogleMaps on iOS pod 'GoogleMaps' # Uncomment this line if you want to support GoogleMaps on iOS pod 'Google-Maps-iOS-Utils' # Uncomment this line if you want to support GoogleMaps on iOS # pod 'RNIap', :path => '../node_modules/react-native-iap' #pod 'RNLocalize', :path => '../node_modules/react-native-localize' pod 'AppAuth', '= 1.2.0' pod 'React-RCTPushNotification', :path => '../node_modules/react-native/Libraries/PushNotificationIOS' pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons' pod 'CodePush', :path => '../node_modules/react-native-code-push' permissions_path = '../node_modules/react-native-permissions/ios' pod 'Permission-Camera', :path => "#{permissions_path}/Camera/Permission-Camera.podspec" pod 'Permission-Notifications', :path => "#{permissions_path}/Notifications/Permission-Notifications.podspec" use_native_modules! end post_install do |installer| installer.pods_project.targets.each do |target| if target.name == 'react-native-google-maps' target.build_configurations.each do |config| config.build_settings['CLANG_ENABLE_MODULES'] = 'No' end end if target.name == "React" target.remove_from_project end end target 'navicotrackappTests' do inherit! :search_paths # Pods for testing end end ``` #### `AppDelegate.m`: ```objc /** * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import "AppDelegate.h" #import #import #import #import #import //#import // This is used for versions of react >= 0.40 #import #import #import //#import #import #import "RNSplashScreen.h" #import #import #import #import #import #import #import @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GMSServices provideAPIKey:@"deleted"]; if ([FIRApp defaultApp] == nil) { [FIRApp configure]; } [[Fabric sharedSDK] setDebug: YES]; [Fabric with:@[CrashlyticsKit]]; [Fabric with:@[[Crashlytics class]]]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil]; RCTSetLogThreshold(RCTLogLevelInfo); RCTSetLogFunction(CrashlyticsReactLogFunction); NSURL *jsCodeLocation; #ifdef DEBUG jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; #else jsCodeLocation = [CodePush bundleURL]; #endif self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.window.backgroundColor = [UIColor whiteColor]; [ReactNativeNavigation bootstrap:jsCodeLocation launchOptions:launchOptions]; [RNSplashScreen show]; return YES; } - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge { #if DEBUG return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; #else return [CodePush bundleURL]; #endif } - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { return [self.authorizationFlowManagerDelegate resumeExternalUserAgentFlowWithURL:url]; } // Required to register for notifications - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { [RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings]; } // Required for the register event. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [RCTPushNotificationManager 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 { [RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; } // Required for the registrationError event. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { [RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error]; } // Required for the localNotification event. - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { [RCTPushNotificationManager didReceiveLocalNotification:notification]; } RCTLogFunction CrashlyticsReactLogFunction = ^( RCTLogLevel level, __unused RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message ) { NSString *log = RCTFormatLog([NSDate date], level, fileName, lineNumber, message); #ifdef DEBUG fprintf(stderr, "%s\n", log.UTF8String); fflush(stderr); #else CLS_LOG(@"REACT LOG: %s", log.UTF8String); #endif int aslLevel; switch(level) { case RCTLogLevelTrace: aslLevel = ASL_LEVEL_DEBUG; break; case RCTLogLevelInfo: aslLevel = ASL_LEVEL_NOTICE; break; case RCTLogLevelWarning: aslLevel = ASL_LEVEL_WARNING; break; case RCTLogLevelError: aslLevel = ASL_LEVEL_ERR; break; case RCTLogLevelFatal: aslLevel = ASL_LEVEL_CRIT; break; } asl_log(NULL, NULL, aslLevel, "%s", message.UTF8String); }; @end ```

Environment

Click To Expand

**`react-native info` output:** ``` warn The following packages use deprecated "rnpm" config that will stop working from next release: - react-native-code-push: https://microsoft.github.io/code-push Please notify their maintainers about it. You can find more details at https://github.com/react-native-community/cli/blob/master/docs/configuration.md#migration-guide. info Fetching system and libraries information... System: OS: macOS 11.1 CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz Memory: 1.49 GB / 16.00 GB Shell: 3.2.57 - /bin/bash Binaries: Node: 10.17.0 - ~/.nvm/versions/node/v10.17.0/bin/node Yarn: 1.17.3 - /usr/local/bin/yarn npm: 6.11.3 - ~/.nvm/versions/node/v10.17.0/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman SDKs: iOS SDK: Platforms: iOS 14.3, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2 Android SDK: API Levels: 23, 25, 26, 27, 28, 29 Build Tools: 23.0.1, 26.0.1, 28.0.3, 29.0.2, 29.0.3, 30.0.0 System Images: android-25 | Google APIs Intel x86 Atom, android-26 | Google APIs Intel x86 Atom, android-27 | Google APIs Intel x86 Atom, android-27 | Google Play Intel x86 Atom, android-28 | Google APIs Intel x86 Atom, android-28 | Google APIs Intel x86 Atom_64, android-29 | Google Play Intel x86 Atom, android-30 | Google APIs Intel x86 Atom_64 Android NDK: 21.3.6528147 IDEs: Android Studio: 4.0 AI-193.6911.18.40.6514223 Xcode: 12.3/12C33 - /usr/bin/xcodebuild npmPackages: react: 16.8.6 => 16.8.6 react-native: 0.60.6 => 0.60.6 ``` - **Platform that you're experiencing the issue on**: - [x] iOS - [ ] Android - [ ] **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/messaging": "^10.4.1",` - **`Firebase` module(s) you're using that has the issue:** - `messagging` - **Are you using `TypeScript`?** - `N`

mikehardy commented 3 years ago

$FirebaseSDKVersion = '7.0.0'

I wouldn't override FirebaseSDKVersion unless you really know what you're doing, and typically I would only every use it to go forward (like, to 7.4.0 right now) temporarily until react-native-firebase ratchets forward.

I'm not sure what is happening with your project but with that stack of dependencies I'd wager something else is doing something unexpected.

I'd wager you cannot reproduce with a simple App.js trying to getToken on a clean reproduction from https://github.com/mikehardy/rnfbdemo/blob/master/make-demo.sh - and that would indicate you have something project-specific going on that isn't this module's fault

We have seen problems with react-native-splash-screen before, you should drop that first with a switch to https://github.com/zoontek/react-native-bootsplash (it has a CLI helper to set it up even, very easy switch).

You're react-native is pretty out of date too, I know RN59->RN60 was tough but all the bumps after that have been almost pleasant, with the the Podfile in particular being nice and clean now, you can use https://react-native-community.github.io/upgrade-helper/ to help with that - I don't believe it will fix your problem though, attempting a clean reproduction then if it works bisecting your dependencies to see which one interacts incorrectly will be how to find it I think

StefanoCremona commented 3 years ago

I upgraded my project to the latest RN version (0.63.4) and I removed as well the FirebaseSDKVersion from my Podfile but I'm still having the same issue. I created from scratch a new RN project with just the react-native-firebase module and I still have the same behaviour. You can checkout this project.

Just to clarify, I have the problem on an IOS ACTUAL DEVICE (Iphone 7 - iOS 14.3). On the Simulator the token comes without problems.

mikehardy commented 3 years ago

Interesting since the Simulator does not support any actual tokens that work. I don't see anywhere in there that you have asked for permission for notifications?

I think that's a necessary step?

StefanoCremona commented 3 years ago

Simulator doesn't receive actual notifications but I always got tokens from tests.

Asking for permissions shouldn't block the process (at least it didn't do it so far) BUT...🥁 ...it worked! 🥰

As I give the app the permissions (latest commit to my project), I get back the token. ❤️

mikehardy commented 3 years ago

I believe the code checks to make sure you have permission before it tries to register for remote messages because otherwise there's no point? Glad it's working for you!

HadiKhalifeh commented 3 years ago

@mikehardy hello,

  async  checkApplicationPermission() {
    const authorizationStatus = await messaging().requestPermission();

    if (authorizationStatus === messaging.AuthorizationStatus.AUTHORIZED) {
      console.log('User has notification permissions enabled.');

    } else if (authorizationStatus === messaging.AuthorizationStatus.PROVISIONAL) {
      console.log('User has provisional notification permissions.');
    } else {
      console.log('User has notification permissions disabled');
    }
  }

 saveFcmToken() {
    messaging()
      .hasPermission()
      .then(enabled => {
        if (enabled) {
          messaging()
            .getToken()
            .then(fcmtoken => {
              if (fcmtoken) {
                console.log(fcmtoken, 'fcmtoken');

                })
              } else {

                // user doesn't have a device token yet
              }
            });
        }

ERROR:[Error: [messaging/unregistered] You must be registered for remote messages before calling getToken, see messaging().registerDeviceForRemoteMessages()

mikehardy commented 3 years ago

@HadiKhalifeh you are posting this on someone else's issue, so the information won't be valid for your problem. If you file a new issue it will ask you for all the information we'll need to troubleshoot your issue. This is important here specifically but in general for any time you file a support request anyway, because for example for all I know, you are on react-native-firebase v5 so I can't make any guesses as to your root cause

I can say that this only happens to users not following documentations / using the APIs correctly, so something is wrong with your code, it will not result in a change in this module - the module code works. So I discourage you from filing a new issue, I encourage you to check, re-check, and check again your code, while comparing with examples of code that works

https://github.com/invertase/react-native-firebase/blob/46556de7ce17ef1d55b52222a907732353addde6/packages/messaging/e2e/messaging.e2e.js#L66-L118