react-native-firebase icon indicating copy to clipboard operation
react-native-firebase copied to clipboard

[🐛] [messaging/unregistered] after messaging().registerDeviceForRemoteMessages() on iOS 16.2

Open antonandreyev opened this issue 3 years ago • 90 comments

Issue

After messaging().registerDeviceForRemoteMessages() use of messaging().getToken() is still throwing [messaging/unregistered] You must be registered for remote messages before calling getToken, see messaging().registerDeviceForRemoteMessages() on iOS 16.2. Probably some older or newer versions are also affected, but not visible in my logs at the moment. If more logs will come I will update the issue.

Code is simple:

messaging()
  .registerDeviceForRemoteMessages() // no-op on Android and if already registered
  .then(() => messaging().getToken())
  .then((t) => {
    setToken(t);
    setIsInitialized(true);
  }) 

UPD:

To clarify about my case: that didn't came overnight. We started to notice this "need to register" error a while ago. We thought we could fix that with explicitly registering and changed code to that is in the opening message. But that didn't help and now we see both "no need to register" and "you need to register". The case is quite rare though.

Using Sentry, here are some extractions from logs:

  • devices: iPhone11,8, iPhone 15.2. All with iOS 16.2
  • example of the log (UPD: read bottom to top): image

UPD: Sentry statistics for 48 hours:

  • 22k users in total
  • 69k user sessions in total
  • 10 users with this error
  • 526 errors of this kind
  • devices: iPhone12,1, iPhone14,3, iPhone11,8, iPhone15,2, iPhone11,6, iPhone13,4
  • OS: 15.6.1, 16.1.1, 16.1.2, 16.2

Project Files

Javascript

Click To Expand

package.json:

{
  "name": "...",
  "version": "0.1.0",
  "license": "UNLICENSED",
  "main": "index.js",
  "private": true,
  "engineStrict": true,
  "engines": {
    "node": "16.19.0",
    "yarn": "1.22.17"
  },
  "scripts": {
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "start": "react-native start --reset-cache",
    "start-cached": "react-native start",
    "lint": "eslint . --ext .tsx,.ts",
    "lint:fix": "yarn lint --fix",
    "tsc": "tsc",
    "test": "jest",
    "test:ci": "jest --passWithNoTests --ci",
    "codegen": "graphql-codegen",
    "translation:gen": "ts-node scripts/fetch-static-translations.ts && prettier --write src/__resources__/i18n_resource.json",
    "prettier": "prettier --check './src/**/*.{ts,tsx,json}'",
    "prettier:fix": "prettier --write './**/*.{ts,tsx,json}'",
    "prepare": "husky install",
    "ci": "rm -rf node_modules && yarn install --prefer-offline --frozen-lockfile && yarn cache clean",
    "postinstall": "patch-package",
    "ios:test": "yarn detox test --configuration ios.debug",
    "ios:build": "yarn detox build --configuration ios.debug",
    "e2e:ios": "yarn ios:build && yarn ios:test",
    "android:test": "yarn detox test --configuration android",
    "android:build": "yarn detox build --configuration android",
    "e2e:android": "yarn android:build && yarn android:test"
  },
  "dependencies": {
    "@apollo/client": "^3.7.3",
    "@formatjs/intl-getcanonicallocales": "^2.0.5",
    "@formatjs/intl-locale": "^3.0.11",
    "@formatjs/intl-numberformat": "^8.3.3",
    "@formatjs/intl-pluralrules": "^5.1.8",
    "@gorhom/bottom-sheet": "~4.4.5",
    "@react-native-async-storage/async-storage": "~1.17.11",
    "@react-native-clipboard/clipboard": "^1.11.1",
    "@react-native-community/art": "^1.2.0",
    "@react-native-firebase/analytics": "^16.4.6",
    "@react-native-firebase/app": "~16.4.6",
    "@react-native-firebase/messaging": "^16.4.6",
    "@react-native-masked-view/masked-view": "^0.2.8",
    "@react-navigation/bottom-tabs": "6.5.0",
    "@react-navigation/native": "6.1.0",
    "@react-navigation/stack": "6.3.8",
    "@sentry/react-native": "4.2.2",
    "accordion-collapse-react-native": "^1.1.1",
    "d3-scale": "^4.0.2",
    "date-fns": "^2.29.3",
    "date-fns-tz": "^1.3.7",
    "expo": "~46.0.17",
    "expo-av": "~12.0.4",
    "expo-constants": "~13.2.4",
    "expo-device": "~4.3.0",
    "expo-file-system": "~14.1.0",
    "expo-font": "~10.2.0",
    "expo-network": "~4.3.0",
    "expo-secure-store": "~11.3.0",
    "expo-splash-screen": "~0.16.2",
    "expo-updates": "~0.14.7",
    "expo-web-browser": "~11.0.0",
    "formik": "^2.2.9",
    "graphql": "^16.6.0",
    "i18next": "^22.4.9",
    "jwt-decode": "^3.1.2",
    "lodash": "^4.17.21",
    "lottie-react-native": "~5.1.3",
    "luxon": "^3.2.1",
    "react": "18.0.0",
    "react-apollo-network-status": "^5.2.1",
    "react-dom": "18.0.0",
    "react-i18next": "^12.1.4",
    "react-native": "0.69.7",
    "react-native-animatable": "^1.3.3",
    "react-native-calendars": "^1.1293.0",
    "react-native-device-info": "^10.3.0",
    "react-native-gesture-handler": "^2.8.0",
    "react-native-indicators": "^0.17.0",
    "react-native-keyboard-aware-scroll-view": "^0.9.5",
    "react-native-linear-gradient": "^2.6.2",
    "react-native-localize": "^2.2.4",
    "react-native-media-query": "^2.0.0",
    "react-native-reanimated": "~2.13.0",
    "react-native-safe-area-context": "^4.4.1",
    "react-native-screens": "^3.18.2",
    "react-native-share": "^8.0.0",
    "react-native-skeleton-placeholder": "5.2.4",
    "react-native-svg": "^13.6.0",
    "react-native-url-polyfill": "^1.3.0",
    "react-native-view-pdf": "^0.14.0",
    "sentry-expo": "^5.0.3",
    "styled-components": "~5.3.6",
    "victory-core": "~36.6.8",
    "victory-native": "~36.6.8",
    "victory-tooltip": "~36.6.8",
    "yup": "^0.32.11",
    "zod": "^3.20.2"
  },
  "devDependencies": {
    "@babel/core": "~7.20.12",
    "@babel/plugin-syntax-flow": "^7.18.6",
    "@babel/plugin-transform-react-jsx": "^7.20.7",
    "@babel/preset-typescript": "~7.18.6",
    "@expo/config": "^7.0.3",
    "@graphql-codegen/cli": "^2.16.3",
    "@graphql-codegen/near-operation-file-preset": "^2.5.0",
    "@graphql-codegen/schema-ast": "^2.6.1",
    "@graphql-codegen/typescript-operations": "^2.5.12",
    "@graphql-codegen/typescript-react-apollo": "~3.3.7",
    "@testing-library/react-native": "^10.1.1",
    "@tsconfig/node16": "^1.0.3",
    "@types/d3-scale": "^4.0.3",
    "@types/jest": "^27.5.2",
    "@types/luxon": "^3.2.0",
    "@types/node": "^17.0.45",
    "@types/react": "~18.0.26",
    "@types/react-native": "~0.69.16",
    "@types/xml2js": "^0.4.11",
    "@typescript-eslint/eslint-plugin": "^5.48.1",
    "@typescript-eslint/parser": "^5.48.1",
    "@xtrctio/eslint-plugin-disallow-date": "^1.0.1",
    "babel-preset-expo": "^9.2.2",
    "cross-fetch": "^3.1.5",
    "detox": "^20.1.1",
    "eslint": "^8.31.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-prettier": "^8.6.0",
    "eslint-config-react-app": "^7.0.1",
    "eslint-loader": "^4.0.2",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-jsx-a11y": "^6.7.0",
    "eslint-plugin-react": "^7.31.11",
    "eslint-plugin-react-hooks": "^4.3.0",
    "expo-cli": "^6.0.8",
    "graphql-tag": "^2.12.6",
    "husky": "^8.0.3",
    "import-sort-style-eslint": "^6.0.0",
    "jest": "27.5.1",
    "jest-junit": "^15.0.0",
    "lint-staged": "^13.1.0",
    "patch-package": "^6.5.1",
    "prettier": "2.8.2",
    "prettier-plugin-import-sort": "^0.0.7",
    "react-native-dotenv": "^3.4.6",
    "react-test-renderer": "18.0.0",
    "ts-node": "^10.9.1",
    "typescript": "~4.9.4"
  },
  "importSort": {
    ".js, .jsx, .ts, .tsx": {
      "style": "eslint",
      "parser": "typescript"
    }
  },
  "lint-staged": {
    "**/*.ts?(x)": [
      "eslint",
      "prettier --write"
    ]
  }
}

firebase.json for react-native-firebase v6:

(no firebase.json)

# N/A

iOS

Click To Expand

ios/Podfile:

  • [ ] I'm not using Pods
  • [x] I'm using Pods and my Podfile looks like:
require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking")
require File.join(File.dirname(`node --print "require.resolve('react-native/package.json')"`), "scripts/react_native_pods")
require File.join(File.dirname(`node --print "require.resolve('@react-native-community/cli-platform-ios/package.json')"`), "native_modules")

platform :ios, '12.4'
install! 'cocoapods', :deterministic_uuids => false

production = ENV["PRODUCTION"] == "1"

require 'json'
podfile_properties = JSON.parse(File.read('./Podfile.properties.json')) rescue {}

target '...' do
  use_expo_modules!
  post_integrate do |installer|
    begin
      expo_patch_react_imports!(installer)
    rescue => e
      Pod::UI.warn e
    end
  end
  config = use_native_modules!
  config = use_frameworks! :linkage => :static

  # Flags change depending on the env values.
  flags = get_default_flags()

  use_react_native!(
    :path => config["reactNativePath"],
    :hermes_enabled => podfile_properties['expo.jsEngine'] == 'hermes',
    :production => production,
    :fabric_enabled => flags[:fabric_enabled],
    # disable due to use_frameworks needed by firebase
    :flipper_configuration => FlipperConfiguration.disabled,
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  pod 'Firebase/Analytics'

  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end

AppDelegate.m:

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <React/RCTLinkingManager.h>
#import <React/RCTConvert.h>
#import <React/RCTAppSetupUtils.h>
#import <Firebase.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  RCTAppSetupPrepareApp(application);

  [FIRApp configure];

  RCTBridge *bridge = [self.reactDelegate createBridgeWithDelegate:self launchOptions:launchOptions];

  NSDictionary *initProps = [self prepareInitialProps];
  UIView *rootView = [self.reactDelegate createRootViewWithBridge:bridge moduleName:@"main" initialProperties:nil];

  if (@available(iOS 13.0, *)) {
      rootView.backgroundColor = [UIColor systemBackgroundColor];
  } else {
      rootView.backgroundColor = [UIColor whiteColor];
  }

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

  [super application:application didFinishLaunchingWithOptions:launchOptions];

  return YES;
}

- (NSDictionary *)prepareInitialProps
{
  NSMutableDictionary *initProps = [NSMutableDictionary new];
  return initProps;
}

- (NSArray<id<RCTBridgeModule>> *)extraModulesForBridge:(RCTBridge *)bridge
{
  // If you'd like to export some custom RCTBridgeModules that are not Expo modules, add them here!
  return @[];
}

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

// Linking API
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
  return [super application:application openURL:url options:options] || [RCTLinkingManager application:application openURL:url options:options];
}

// Universal Links
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
  BOOL result = [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
  return [super application:application continueUserActivity:userActivity restorationHandler:restorationHandler] || result;
}

// Explicitly define remote notification delegates to ensure compatibility with some third-party libraries
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  return [super application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

// Explicitly define remote notification delegates to ensure compatibility with some third-party libraries
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  return [super application:application didFailToRegisterForRemoteNotificationsWithError:error];
}

// Explicitly define remote notification delegates to ensure compatibility with some third-party libraries
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  return [super application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

@end


Android

Click To Expand

N/A


Environment

Click To Expand

react-native info output:

System:
    OS: Windows 10 10.0.22621
    CPU: (20) x64 12th Gen Intel(R) Core(TM) i7-12700H
    Memory: 9.29 GB / 31.68 GB
  Binaries:
    Node: 16.19.0 - C:\Users\ANTON~1.AND\AppData\Local\Temp\yarn--1673424499379-0.7430549663942487\node.CMD
    Yarn: 1.22.17 - C:\Users\ANTON~1.AND\AppData\Local\Temp\yarn--1673424499379-0.7430549663942487\yarn.CMD
    npm: 8.19.3 - C:\Program Files\nodejs\npm.CMD
    Watchman: Not Found
  SDKs:
    Android SDK:
      API Levels: 27, 30, 31, 33
      Build Tools: 27.0.3, 30.0.2, 30.0.3, 31.0.0, 33.0.0
      System Images: android-27 | Intel x86 Atom_64, android-27 | Google APIs Intel x86 Atom, android-30 | Google APIs Intel x86 Atom, android-31 | Google APIs Intel x86 Atom_64       
      Android NDK: Not Found
    Windows SDK: Not Found
  IDEs:
    Android Studio: Not Found
    Visual Studio: Not Found
  Languages:
    Java: 11.0.15
  npmPackages:
    @react-native-community/cli: Not Found
    react: 18.0.0 => 18.0.0
    react-native: 0.69.7 => 0.69.7
    react-native-windows: Not Found
  npmGlobalPackages:
    *react-native*: Not Found
  • 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:
    • 16.4.6
  • Firebase module(s) you're using that has the issue:
    • messaging
  • Are you using TypeScript?
    • Y & 4.9.4


antonandreyev avatar Jan 11 '23 08:01 antonandreyev

Hello @antonandreyev in my case I'm getting the following error after running await messaging().getToken();, had some reports of users having issues on iOS. Then tested on simulator and got the error in version 16.2 of iOS NativeFirebaseError: [messaging/unknown] The operation couldn’t be completed. Invalid fetch response, expected 'token' or 'Error' key.

livnunes avatar Jan 11 '23 13:01 livnunes

@livnunes @antonandreyev Your experience replicates for me iPhone 14 (iOS 16.0) emulator, since this morning, I'm getting the exact same error:

NativeFirebaseError: [messaging/unknown] The operation couldn’t be completed. Invalid fetch response, expected 'token' or 'Error' key

There have been no Firebase-related library changes in our RN project in the time frame in question. I did how ever run a fresh pod install this morning as part of some unrelated 3rd party library changes. Podfile.lock is unchanged w.r.t. Firebase.

For what it's worth the project is on RN 0.68.5 with RN Firebase 13.0.1.

We were in the process of looking into the RN Firebase upgrade, but need to complete our assessment of the breaking change with use_frameworks! in RN Firebase 15.

tomwanzek avatar Jan 11 '23 17:01 tomwanzek

Currently we can not replicate it in STAGING or PROD, but if this is due to some "unpinned" deep dependency that gets updated to a disfunctional/incompatible native library with the next Deployment CI run, we would have a real 🔥.

The bug stops the App cold when the user logs in, and we try to getToken().

tomwanzek avatar Jan 11 '23 17:01 tomwanzek

@mikehardy By any chance, are you aware of anything that might have caused this sudden change "overnight"? 🙇

tomwanzek avatar Jan 11 '23 17:01 tomwanzek

To clarify about my case: that didn't came overnight. We started to notice this "need to register" error a while ago. We thought we could fix that with explicitely registering and changed code to that is in the opening message. But that didn't help and now we see both "no need to register" and "you need to register". The case is quite rare though, 100 errors in 10000 sessions in past 24 hours.

antonandreyev avatar Jan 11 '23 17:01 antonandreyev

@antonandreyev Thanks for the clarification and in order to keep your issue what it was meant to be, I have opened: https://github.com/invertase/react-native-firebase/issues/6830 cc @livnunes @mikehardy

tomwanzek avatar Jan 11 '23 18:01 tomwanzek

Hello, the above issue could happen because of unresolved issue https://github.com/invertase/react-native-firebase/issues/5377

Please check your Podfile and if you have abstract_target there -> that's the case. It probably skips the [RNFB] Core Configuration script phaze during pod install

r0ssIV avatar Jan 17 '23 21:01 r0ssIV

@rivaros the Podfile is attached to the issue and there is no abstract_target in it. Also this issue is happening only to a minority of users, so I doubt this is a linking issue.

It seems much more like the actual issue is that the token fails to be fetched or firebase/messaging fails to be registered in some special cases and the error message is misleading.

antonandreyev avatar Jan 20 '23 07:01 antonandreyev

@antonandreyev did not see you included Podfile. So yes, indeed your case is different.

Have noticed that you implemented didRegisterForRemoteNotificationsWithDeviceToken. Does it play well with swizzling https://firebase.google.com/docs/cloud-messaging/ios/client#token-swizzle-disabled ?

r0ssIV avatar Jan 20 '23 07:01 r0ssIV

@rivaros it does. My implementation is just a part of expo setup instructions. As I understand when swizzling is enabled (default) there is no need to change anything in didRegisterForRemoteNotificationsWithDeviceToken. At least it does work well as per our monitoring.

antonandreyev avatar Jan 25 '23 07:01 antonandreyev

Same problem here, any solutions so far ? I'm using React Native CLI.

await messaging().registerDeviceForRemoteMessages(); i got this error:

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.

if I remove registerDeviceForRemoteMessage

I got next error:

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

dragoshuniq avatar Jan 27 '23 10:01 dragoshuniq

@dragoshuniq one is a warning ("that it may not be necessary"), and one is an error ("you are not registered"). There are a few cases where you do actually not need to register, for example if you have AppDelegate swizzling disabled for firebase FCM or similar, and it appears you have one of them for whatever reason.

So, leave that call in.

mikehardy avatar Jan 27 '23 12:01 mikehardy

Our user experience the same issue. It only occurs to a small group of users.

Sentry log:

device iPhone 11 Pro
device.family iOS
event.environment javascript
event.origin javascript
hermes true
os iOS 16.2
Message error_register_device with message: [messaging/unregistered] You must be registered for remote messages before calling getToken, see messaging().registerDeviceForRemoteMessages().

RNFirebasea version: 16.7.0

The issue first appeared Feb. 10 in our logs. In the weeks before, there has been no update to the app regarding RNFirebase.

idlework avatar Feb 15 '23 10:02 idlework

@idlework that is a legitimate error case that must be handled now with the new strict requirement that you must have an APNS token before getting an FCM token. I am not 100% sure how many cases there are where registration for remote notifications can fail, but it is clearly possible. Perhaps a network error and a retry would work. Perhaps there is a permissions denial by the user? I'm not sure. But, if you cannot get an APNS token, an FCM token is by definition useless and those types of FCM tokens are not issued now, so this error should be handled with some messaging to the user (for example "such and such feature of our app relies on remote notifications and there was an error registering for remote notificaitons. Perhaps check such and such ...")

mikehardy avatar Feb 15 '23 18:02 mikehardy

@mikehardy Thanks for the quick and clear answer. I'll implement a check to see what the user response is for the notifications request.

idlework avatar Feb 16 '23 14:02 idlework

@mikehardy It might be worth chiming in that after upgrading to 17.3.1 we started getting the You must be registered for remote messages before calling getToken, see messaging().registerDeviceForRemoteMessages() error despite calling it in this order

await messaging.registerDeviceForRemoteMessages();
const token = await messaging.getToken();

But it was actually due to it being called on an iOS SIMULATOR. It might be worth noting somewhere that the new changes around this stuff seem to make simulators throw this error now. The same exact code works fine on physical devices for us.

marcfrankel avatar Feb 24 '23 23:02 marcfrankel

Simulators on intel Macs will need to call setAPNSToken now, as there is no token available for them, they do not support APNS or FCM (thus, the error is real). You can set a bogus token in though, we do that for our testing purposes and confirmed via collaboration with firebase-ios-sdk this is a valid strategy: https://github.com/invertase/react-native-firebase/blob/00185a37bc554f9bcb6feb6434d6c9c75ed51a3a/packages/messaging/e2e/messaging.e2e.js#L203

Cool (in my opinion) news though: on M1 macs using latest macOS (ventura) and iOS (in simulator) the Simulator actually supports FCM/APNS - so it works! I tested that personally and cleaned out all the stuff in our code here to enable it.

Both of those things could be called out in the docs more strongly yes - if you remember what page you were on when you were referring to this documentation and got hung up, you might be the best person as I've lost all perspective - there's an edit button at the top of each page and github web UI for docs PRs is just a 1-2 minute thing. I'll shepherd it through

mikehardy avatar Feb 25 '23 22:02 mikehardy

@mikehardy I don't think there was a particular page on the documentation, but if it's not too late I'd just add a line to the break change notice in the release notes. I was simply following that when I came across this issue. So perhaps just one line that even if you call registerDeviceForRemoteMessages before getToken it will still fail on intel simulators?

marcfrankel avatar Feb 26 '23 22:02 marcfrankel

Hello @mikehardy , I got the same issue, just upgrade my react native to the latest:

  • "react": "18.2.0",
  • "react-native": "0.71.4",
  • "@react-native-firebase/app": "17.3.2",
  • "@react-native-firebase/messaging": "17.3.2",

LuongTruong avatar Mar 14 '23 15:03 LuongTruong

@LuongTruong there are quite a few things ("issues") discussed, could you be more specific by including the actual message contents you receive, along with a minimal reproduction that would show the error if placed in an App.js? Do make sure that you have requested + received notification permission from the user, have the correct entitlements, are in an environment where you can either get an APNS token (real device, or current simulator on current macOS on Apple Silicon machine) or you have set an APNS token

mikehardy avatar Mar 14 '23 15:03 mikehardy