React Native 0.66 iOS crashes on AppDelegate RCTRootView init - ios

I'm trying to upgrade our RN project to 0.66 (from 0.63). When I build the project in debug mode, the app crashes on startup due to uncaught exception 'NSInvalidArgumentException', reason: '-[REAEventDispatcher setBridge:]: unrecognized selector sent to instance 0x600002f51cc0' when initializing the RCTRootView in the AppDelegate.m file (entire file at the end).
After some googling, I found the unrecognized selector bit is because some function is undefined on an object. The error is marked in the code, its about halfway through the file.
I need some help finding out why this function isn't available (or what else is wrong). As far as I can see, the files have an implementation of the functions that are called. Am I missing any imports? Not that well versed in Swift, only used it in combination with React Native.
I haven't made a reproducible example, but I hope someone else has come over this already in porting to this version. If you need any more information, please ask. I've also attached the podfile below the relevant file.
Appdelegate.m
#import "AppDelegate.h"
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <React/RCTLinkingManager.h>
#import "RNBootSplash.h"
#import <GoogleMaps/GoogleMaps.h>
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>
#import <Firebase.h>
#ifdef FB_SONARKIT_ENABLED
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
static void InitializeFlipper(UIApplication *application) {
FlipperClient *client = [FlipperClient sharedClient];
SKDescriptorMapper *layoutDescriptorMapper =
[[SKDescriptorMapper alloc] initWithDefaults];
[client addPlugin:[[FlipperKitLayoutPlugin alloc]
initWithRootNode:application
withDescriptorMapper:layoutDescriptorMapper]];
[client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
[client addPlugin:[FlipperKitReactPlugin new]];
[client addPlugin:[[FlipperKitNetworkPlugin alloc]
initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
[client start];
}
#endif
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if([FIRApp defaultApp] == nil){
[FIRApp configure];
}
[GMSServices provideAPIKey:#"AIzaSyC-BV0Dp46BQ1iP1HRws-oP_90FV0Aewfo"]; // add this line using the api key obtained from Google Console
#ifdef FB_SONARKIT_ENABLED
InitializeFlipper(application);
#endif
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]
//This is where the application crashes
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:#"Flatz"
initialProperties:nil];
if (#available(iOS 13.0, *)) {
rootView.backgroundColor = [UIColor systemBackgroundColor];
} else {
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];
[RNBootSplash initWithStoryboard:#"LaunchScreen" rootView:rootView]; // <- initialization using the storyboard file name
// Define UNUserNotificationCenter
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
return YES;
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
#ifdef FB_SONARKIT_ENABLED
return
[[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index"
fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:#"main"
withExtension:#"jsbundle"];
#endif
}
// 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 localNotification event
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
[RNCPushNotificationIOS didReceiveNotificationResponse:response];
}
//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
return [RCTLinkingManager application:application openURL:url options:options];
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity
restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
return [RCTLinkingManager application:application
continueUserActivity:userActivity
restorationHandler:restorationHandler];
}
#end
Podfile
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/#react-native-community/cli-platform-ios/native_modules'
platform :ios, '11.0'
target 'Flatz' do
# No individual tracking of people or their phones
$RNFirebaseAnalyticsWithoutAdIdSupport=true
# React Native Maps dependencies
rn_maps_path = '../node_modules/react-native-maps'
pod 'react-native-google-maps', :path => rn_maps_path
pod 'GoogleMaps'
pod 'Google-Maps-iOS-Utils'
config = use_native_modules!
use_react_native!(
:path => config["reactNativePath"],
:hermes_enabled => true
)
target 'FlatzTests' do
inherit! :complete
# Pods for testing
end
# Enables Flipper.
#
# Note that if you have use_frameworks! enabled, Flipper will not work and
# you should disable these next few lines.
use_flipper!({ 'Flipper-Folly' => '2.5.3', 'Flipper' => '0.87.0', 'Flipper-RSocket' => '1.3.1' })
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
#1
deployment_target = config.build_settings['IPHONEOS_DEPLOYMENT_TARGET']
#2
target_components = deployment_target.split
#3
if target_components.length > 0
#4
target_initial = target_components[0].to_i
#5
if target_initial < 9
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = "9.0"
end
end
end
end
installer.pods_project.build_configurations.each do |config|
config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
end
end
permissions_path = '../node_modules/react-native-permissions/ios'
pod 'Permission-Camera', :path => "#{permissions_path}/Camera"
end

As jnpdx pointed out, I needed to follow the upgrade helper. Turns out there were quite a few steps I had missed doing it without it.

For me I had the iOS Deployment target under build settings on 9, while on the Podfile on 11. Changing to 11 solved the problem, see how to change iOS Deployment target. Also, remember to npx react-native-clean-project

Related

DynamicLinks iOS: await dynamicLinks().getInitialLink() works on debug, but doesn't work on release mode

await dynamicLinks().getInitialLink() works in debug mode, but doesn't work in release mode on iOS.
await dynamicLinks().getInitialLink() work fine for android debug and release mode but when i use dynamic link in debug mode it work fine but when i create release mode for app this will return always null. not getting after sometimes of wait because i research on that issue somebody getting link after some wait of times but in my case it will not return any link after wait of sometimes.
I spent a day for finding the solution for that but nothing work for me. I tried all most the solution which mention in #2660 #4548 #3450 but not work any solution for me.
Project Files
export const getInitialLink = async ()=> {
const link = await dynamicLinks().getInitialLink();
const id = onHandleDynamicLink(link);
return id;
};
export const onHandleDynamicLink = link => {
if (link) {
const linkUrl = url.parse(link.url, true);
const VideoId = linkUrl.path.split('/')[2];
return VideoId;
}
return null;
};
import {getInitialLink} from '../../helpers/dynamicLinksHelper';
const Id = await getInitialLink();`
package.json:
"#react-native-firebase/app": "^16.4.6",
"#react-native-firebase/dynamic-links": "^16.4.6",
"react-native": "0.64.2",
iOS
source 'https://github.com/CocoaPods/Specs.git
target 'project' do
config = use_native_modules!
use_react_native!(
:path => config[:reactNativePath],
# to enable hermes on iOS, change `false` to `true` and then install pods
:hermes_enabled => false
)
pod 'Firebase', :modular_headers => true
pod 'FirebaseCoreInternal', :modular_headers => true
pod 'GoogleUtilities', :modular_headers => true
pod 'FirebaseCore', :modular_headers => true
# add the Firebase pod for Google Analytics
# pod 'Firebase/Analytics'
# pod 'react-native-webview', :path => '../node_modules/react-native-webview'
# pod 'RNAWSCognito', :path => '../node_modules/amazon-cognito-identity-js'
# pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
# pod 'RNDeviceInfo', :path => '../node_modules/react-native-device-info'
target 'newslineisitanywayTests' do
inherit! :complete
# Pods for testing
end
# Enables Flipper.
#
# Note that if you have use_frameworks! enabled, Flipper will not work and
# you should disable the next line.
use_flipper!()
post_install do |installer|
react_native_post_install(installer)
end
end
AppDelegate.m:
#import "AppDelegate.h"
#import <React/RCTLinkingManager.h>
#import <RNFBDynamicLinksAppDelegateInterceptor.h>
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>
#import Firebase;
#import "RNFBMessagingModule.h"
#ifdef FB_SONARKIT_ENABLED
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>
static void InitializeFlipper(UIApplication *application) {
FlipperClient *client = [FlipperClient sharedClient];
SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
[client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
[client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
[client addPlugin:[FlipperKitReactPlugin new]];
[client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
[client start];
}
#endif
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[RNFBDynamicLinksAppDelegateInterceptor sharedInstance];
#ifdef FB_SONARKIT_ENABLED
InitializeFlipper(application);
#endif`your text`
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
NSDictionary *appProperties = [RNFBMessagingModule addCustomPropsToUserProps:nil withLaunchOptions:launchOptions];
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:#"newslineisitanyway"
initialProperties:appProperties];
if (#available(iOS 13.0, *)) {
rootView.backgroundColor = [UIColor systemBackgroundColor];
} else {
rootView.backgroundColor = [UIColor whiteColor];
}
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
[FIRApp configure];
return YES;
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[FBSDKAppEvents activateApp];
}
// 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 localNotification event
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
// [RNCPushNotificationIOS didReceiveNotificationResponse:response];
}
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:#"main" withExtension:#"jsbundle"];
#endif
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity
restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
return [RCTLinkingManager application:application
continueUserActivity:userActivity
restorationHandler:restorationHandler];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
RNFBDynamicLinksAppDelegateInterceptor *interceptor = [RNFBDynamicLinksAppDelegateInterceptor sharedInstance];
if (url && !interceptor.initialLinkUrl)
{
FIRDynamicLink *dynamicLink = [[FIRDynamicLinks dynamicLinks] dynamicLinkFromCustomSchemeURL:url];
if (dynamicLink.url)
{
interceptor.initialLinkUrl = dynamicLink.url.absoluteString;
interceptor.initialLinkMinimumAppVersion = dynamicLink.minimumAppVersion == nil ? [NSNull null] : dynamicLink.minimumAppVersion;
}
}
return [RCTLinkingManager application:application openURL:url options:options];
return YES;
}
#end`
Environment
react-native info output:
Platform that you're experiencing the issue on:
[x] iOSyour text
Are you using TypeScript?
NO

No known class method for selector 'didReceiveNotificationResponse:' IOS Notifications

I've been trying to setup notifications on an IOS app for several days and I'm facing many issues.
One that i cannot figure out how it happens is the following :
In appDelegate.m :
Error
I do not understand the error given the fact that I'm a React-native developper but it seems really strange.
Here is my full AppDelegate.m File :
#import "AppDelegate.h"
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <React/RCTLinkingManager.h>
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>
#ifdef FB_SONARKIT_ENABLED
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>
#import <GoogleMaps/GoogleMaps.h>
static void InitializeFlipper(UIApplication *application) {
FlipperClient *client = [FlipperClient sharedClient];
SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
[client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
[client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
[client addPlugin:[FlipperKitReactPlugin new]];
[client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
[client start];
}
#endif
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
if ([url.path isEqualToString:#"/"]) {
NSString *fixedString = [NSString stringWithFormat:#"%#://?%#", url.scheme, url.query]; //Pour solve l'issue suivante : https://github.com/aws-amplify/amplify-js/issues/7468
NSURL *fixedURL = [NSURL URLWithString:fixedString];
return [RCTLinkingManager application:application openURL:fixedURL options:options];
}
return [RCTLinkingManager application:application openURL:url options:options];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[GMSServices provideAPIKey:#"xxxxxx"]; // add this line using the api key obtained from Google Console
#ifdef FB_SONARKIT_ENABLED
InitializeFlipper(application);
#endif
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:#"Villeo"
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 = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
// Define UNUserNotificationCenter
UNUserNotificationCenter *center =
[UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
return YES;
}
// Called when a notification is delivered to a foreground app.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:
(void (^)(UNNotificationPresentationOptions options))
completionHandler {
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge |
UNNotificationPresentationOptionAlert);
}
// 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];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler {
[RNCPushNotificationIOS didReceiveNotificationResponse:response];
completionHandler();
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:#"main" withExtension:#"jsbundle"];
#endif
}
#end
I've followed the best I could the setup instructions from : https://github.com/react-native-push-notification/ios#augment-appdelegate
Thanks in advance 🤝

Notification not receiving in iOS for react native project

I have a react native project. I am able to receive the FCM token successfully but when trying to send a notification, the app doesn't receive the notification.
The steps I followed are as below:
Created a project in Firebase Console.
Added the Firebase .plist in the projectName through Xcode.
ran npm install --save react-native-firebase
Added in podfile: pod ‘Firebase/Core’
ran pod install
Update AppDelegate.m with #import <Firebase.h> and [FIRApp configure];
Added the APNS in the Firebase Dashboard for iOS App Cloud Messaging.
Updated the capabilities with Push Notification and Background Modes > Remote notification
In info.plist FIRAnalyticsDebugEnabled, FirebaseAppDelegateProxyEnabled, FirebaseScreenReportingEnabled is set to No
using const fcmToken = await firebase.messaging().getToken(); I am able to get token.
Below is the code for the notification listener.
async createNotificationListeners() {
/*
* Triggered when a particular notification has been received in foreground
* */
this.notificationListener = firebase.notifications().onNotification((notification) => {
const {
title,
body
} = notification;
this.custom_data = notification.data;
const localNotification = new firebase.notifications.Notification({
show_in_foreground: true,
})
.setSound('default')
.setNotificationId(notification.notificationId)
.setTitle(notification.title)
.setBody(notification.body)
firebase.notifications()
.displayNotification(localNotification)
.catch(err => Alert.alert(err));
});
/*
* If your app is in foreground and background, you can listen for when a notification is clicked / tapped / opened as follows:
* */
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
if ("title" in notificationOpen.notification.data) {
const {
title,
body,
secret_key,
user_id,
realm_id,
user_os,
user_location
} = notificationOpen.notification.data;
this.props.navigation.navigate('Verify', {
title: title,
body: body,
secret_key: secret_key,
user_id: user_id,
realm_id: realm_id,
user_os: user_os,
user_location: user_location
});
} else {
const {
title,
body,
secret_key,
user_id,
realm_id,
user_os,
user_location
} = this.custom_data;
this.props.navigation.navigate('Verify', {
title: title,
body: body,
secret_key: secret_key,
user_id: user_id,
realm_id: realm_id,
user_os: user_os,
user_location: user_location
});
}
});
/*
* If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
* */
const notificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
const {
title,
body,
secret_key,
user_id,
realm_id,
user_os,
user_location
} = notificationOpen.notification.data;
this.props.navigation.navigate('FCM', {
title: title,
body: body,
secret_key: secret_key,
user_id: user_id,
realm_id: realm_id,
user_os: user_os,
user_location: user_location
});
}
/*
* Triggered for data only payload in foreground
* */
this.messageListener = firebase.messaging().onMessage((message) => {
console.log("JSON.stringify:", JSON.stringify(message));
});
}
Please do let me know if more details required.
EDIT
I have updated the code. Now I am able to get firebase.messaging().onMessage() code working and receive a trigger in the foreground. Still unable to get the notification when the app is in the background. Below is the change which I have made.
const fcmToken = await firebase.messaging().getToken();
firebase.messaging().ios.registerForRemoteNotifications().then((flag)=>{
console.log("registered", flag);
}).catch((err)=>{
console.log("message", err);
});
AppDelegate.m
#import "AppDelegate.h"
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <Firebase.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
[RNFirebaseNotifications configure];
//[FIRApp configure];
[Fabric with:#[[Crashlytics class]]];
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:#"CymmAuth"
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];
return YES;
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:#"main" withExtension:#"jsbundle"];
#endif
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}
-(void) userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
[[RNFirebaseMessaging instance] didReceiveRemoteNotification:response.notification.request.content.userInfo];
completionHandler();
}
#end
Do let me know if I am missing anything. firebase.notifications().onNotification() doesn't get triggered
After referring multiple articles from google, I managed to solve the problem. I have realized that many are facing the issue. So I am mentioning all the steps and code which I have implemented.
App Id and APNs key need to be generated from Apple's Developer Account. After generating App Id and APNs key, add the generated APNs key in your Firebase Project. In the App Id where you have added Push Notification as capability configure it with developer and production service SSL Certificates.
Also, make sure the GoogleService-Info.plist file is added in your iOS project through Xcode under the project name.
In Signing & Capabilities of Xcode add Push Notifications and Background Modes > Remote notification, Background fetch, Background processing (confirm if the capabilities are reflecting in both Debug and Release).
In info.plist FIRAnalyticsDebugEnabled, FirebaseAppDelegateProxyEnabled, FirebaseScreenReportingEnabled set to No
In Xcode Scheme > Edit Scheme... check if Run modes Build Configuration is set to Debug. This will help to generate the console in Xcode when you debug the app in your device.
In React App npm install --save react-native-firebase
Update pods in Podfile of ios project
pod 'Firebase/Core'
pod 'Firebase/Messaging'
pod 'Firebase/Crashlytics'
pod 'Firebase/Analytics'
pod 'RNFirebase', :path => '../node_modules/react-native-firebase/ios'
cd ios > pod install
Code to get FCM token and APNs token.
const fcmToken = await firebase.messaging().getToken();
console.log("FCM_Token", fcmToken);
firebase.messaging().ios.registerForRemoteNotifications().then((flag) => {
firebase.messaging().ios.getAPNSToken().then(apns => {
console.log("Apn Token", apns);
}).catch((e) => {
})
}).catch((err) => {
console.log("message", err);
});
AppDelegate.m
#import "AppDelegate.h"
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <Firebase.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[RNFirebaseNotifications configure];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
[application registerForRemoteNotifications];
[Fabric with:#[[Crashlytics class]]];
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:#"CymmAuth"
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];
return YES;
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:#"main" withExtension:#"jsbundle"];
#endif
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[FIRMessaging messaging].APNSToken = deviceToken;
}
#end
AppDelegate.h
#import <React/RCTBridgeDelegate.h>
#import <UIKit/UIKit.h>
#import <Firebase.h>
#import <UserNotifications/UserNotifications.h>
#import UserNotifications;
#interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate>
#property (nonatomic, strong) UIWindow *window;
#end
This will get the notification on your Apple Device.
To test the notification, FCM token validity, and to regenerate valid FCM token from APNs token, there is an API call of Firebase. This could be an additional help to test.
Send Push Notification
Endpoint: https://fcm.googleapis.com/fcm/send
Type: POST
Header: Authorization: "key:fcm_server_key"
Body: {
"to": "fcm_token",
"content_available": true,
"mutable_content": true,
"data": {
"message": "Batman!",
"mediaUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/FloorGoban.JPG/1024px-FloorGoban.JPG"
},
"notification": {
"body": "Enter your message",
"sound": "default"
}
}
Validate your FCM token
Endpoint: https://iid.googleapis.com/iid/info/your_fcm_token
Type: GET
Header: Authorization: "key:fcm_server_key"
Regenerate FCM token using APNs token
Endpoint: https://iid.googleapis.com/iid/v1:batchImport
Type: POST
Header: Authorization: "key:fcm_server_key"
Body: {
"application":"package Id",
"sandbox":true,
"apns_tokens":[
"apnstoken 1","apnstoken 2"
]
}
I hope this helps. Thank you.

react-native-firebase notifications().onNotification() is never called in ios

I sent test messages from firebase console but firebase.notifications().onNitification((notification :Notification)=>{
console.log(notification);
}) was never called.
The versions
- "react-native": "^0.61.2",
- "react-native-firebase": "^5.5.6",
podfile
1. pod 'RNFirebase', :path => '../node_modules/react-native-firebase/ios'
2. pod 'Firebase/Core', '~> 6.3.0'
3. pod 'Firebase/Messaging', '~> 6.3.0'
What I did are...
I uploaded an APN key to the firebase project.
I put GoogleService-info.plist in my project.
Here is my AppDelegate.m
#import "AppDelegate.h"
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <GoogleMaps/GoogleMaps.h>
#import <Firebase.h>
#import <FirebaseMessaging.h>
#import "RNFirebaseMessaging.h"
#import "RNFirebaseNotifications.h"
#import "RNSplashScreen.h"
#import Firebase;
#import UserNotifications;
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[RNFirebaseNotifications configure];
[GMSServices provideAPIKey:#""];
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:#""
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];
[RNSplashScreen show];
return YES;
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:#"main" withExtension:#"jsbundle"];
#endif
}
#end
Here's my code
this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
alert('in method')
console.log("onNotification");
console.log(notification);
notification.setSound("default");
notification.ios.setBadge(notification.ios.badge ? notification.ios.badge + 1 : 0);
firebase.notifications().displayNotification(notification);
});
Just a few wild guesses base on the information you've provided:
1) In the capabilities tab in Xcode, turn on:
a) Push Notifications
b) Background Modes - Check only Remote Notifications
2) Check build phases:
a) In Project Navigator, right click Libraries > Add Files To . Navigate to /node_modules/react-native-firebase/ios/. Select RNFirebase.xcodeproj and click Add button.
b) Again click “+”, select libRNFirebase.a and add it. If you are unable to find it, clean and build project.
c) Go to Build Settings, find Header Search Path, double click its value and press “+” button. Add following line there:
$(SRCROOT)/../node_modules/react-native-firebase/ios/RNFirebase
d) Use “Cmd +Shift + Enter + K” keys to clear cache and then build project. Now firebase dependencies should be recognized by xcode.
e) Use “Cmd +Shift + Enter + K” keys to clear cache and then build project. Now firebase dependencies should be recognized by xcode.

iOS React Native Firebase (Invertase) Google Sign in build fails

I have been trying for sometime to get React Native Firebase Google Sign in work through the inverstase packages. I have followed the documentation in order that it is read and various other orders such as starting with the SDK
https://rnfirebase.io/docs/v4.3.x/auth/social-auth#Google
https://github.com/react-native-community/react-native-google-signin
https://github.com/react-native-community/react-native-google-signin/blob/master/ios-guide.md
My project setup looks like the following:
Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'giftdrop' do
### GOOGLE MAPS ###
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 'yoga', path: "#{rn_path}/ReactCommon/yoga/yoga.podspec"
pod 'React', path: rn_path, subspecs: [
'Core',
'CxxBridge',
'DevSupport',
'RCTActionSheet',
'RCTAnimation',
'RCTGeolocation',
'RCTImage',
'RCTLinkingIOS',
'RCTNetwork',
'RCTSettings',
'RCTText',
'RCTVibration',
'RCTWebSocket',
]
# React Native third party dependencies podspecs
pod 'DoubleConversion', :podspec => "#{rn_path}/third-party-podspecs/DoubleConversion.podspec"
pod 'glog', :podspec => "#{rn_path}/third-party-podspecs/glog.podspec"
# If you are using React Native <0.54, you will get the following error:
# "The name of the given podspec `GLog` doesn't match the expected one `glog`"
# Use the following line instead:
#pod 'GLog', :podspec => "#{rn_path}/third-party-podspecs/GLog.podspec"
pod 'Folly', :podspec => "#{rn_path}/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 # Remove this line if you don't want to support GoogleMaps on iOS
pod 'GoogleMaps' # Remove this line if you don't want to support GoogleMaps on iOS
pod 'Google-Maps-iOS-Utils' # Remove this line if you don't want to support GoogleMaps on iOS
### FIREBASE ###
pod 'Firebase/Core'
pod 'Firebase/Firestore'
pod 'Firebase/Auth'
pod 'RNShare', :path => '../node_modules/react-native-share'
pod 'Firebase/Messaging'
pod 'react-native-version-number', :path => '../node_modules/react-native-version-number'
pod 'GoogleSignIn'
pod 'RNGoogleSignin', :path => '../node_modules/react-native-google-signin'
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
end
AppDelegate.m
#import "AppDelegate.h"
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <React/RCTLinkingManager.h>
#import <Firebase.h>
#import <React/RCTPushNotificationManager.h> // NPM module Notifications
#import "RNFirebaseNotifications.h" // Firebase Notifications
#import "RNFirebaseMessaging.h" // Firebase remote Notifications
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import "RNGoogleSignin.h"
#import GoogleMaps;
#implementation AppDelegate
- (void)applicationDidBecomeActive:(UIApplication *)application {
[FBSDKAppEvents activateApp];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:#"notFirstRun"]) {
[defaults setBool:YES forKey:#"notFirstRun"];
[defaults synchronize];
[[FIRAuth auth] signOut:NULL];
}
[RNFirebaseNotifications configure]; // Firebase Notifications
NSURL *jsCodeLocation;
[GMSServices provideAPIKey:#"AIzaSyDLSohfIWoBOSmzpAHUqDSL-puku7LDP6U"];
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:#"giftdrop"
initialProperties:nil
launchOptions:launchOptions];
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];
[Fabric with:#[[Crashlytics class]]];
return YES;
}
// deeplinking for fb and normal
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation
]
|| [RNGoogleSignin application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation
];
return handled || [RCTLinkingManager application:application openURL:url
sourceApplication:sourceApplication annotation:annotation];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// 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];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
[[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}
#end
Frameworks
URL Types
I changes the string out for security but I got it from GoogleInfo.plist REVERSED_CLIENT_ID
Linked Libraries
Framework Search Paths
The string addition according to the docs, is added to both release and debug
Firebase itself works fine, as does the Facebook SDK, but no matter how I do this my project fails to build with various errors depending on what order I do things.
Most common is CFBundler error, duplicate libraries, sometimes no error at all just build failed
Update
Seems Xcode is reporting #import "RNGoogleSignin.h" not found
I had to manually link the project and its libraries to solve the issue, as seen in docs here https://github.com/react-native-community/react-native-google-signin
Secondly I also had to set #import "RNGoogleSignin.h" as #import <GoogleSignIn/GoogleSignIn.h> which differs from the documentation.

Resources