Not receiving notification when app in background (iOS react-native) - ios

I am implementing react-native-firebase to one of my projects and trying to add notification feature in it. But i am having problem getting notifications. When i send notification using firebase api "https://fcm.googleapis.com/fcm/send", i get notification when the app is in foreground. But when the app is in background and send the notification, i don't get any. But as soon as i open the app, i receive the notification.
I have already copied the googleservice-info.plist file and uploaded the auth key in firebase.
My main js code :
messagaing.hasPermission()
.then((enabled) => {
if (enabled) {
messagaing.getToken()
.then(async token => {
const deviceId = await AsyncStorage.getItem('deviceId');
if (!deviceId) {
this.registerTokenOnServer(token)
} else {
this.setState({
deviceId
})
}
console.log('fcm token', token)
})
.catch(error => { console.log('fcm error', error) })
} else {
messagaing.requestPermission()
.then(() => { console.log('fcm token') })
.catch(() => { console.log('fcm error') })
}
})
.catch(error => {
console.log('fcm error', error)
})
messagaing.onMessage((message) => {
console.log('fcm noti on message data', message)
let notification_to_be_displayed = new firebase.notifications.Notification({
sound: 'default',
show_in_foreground: true,
title: message._data.title,
body: message._data.message,
});
firebase.notifications().displayNotification(notification_to_be_displayed);
firebase.notifications().onNotificationOpened((notificationOpen) => {
const notification = notificationOpen.notification;
console.log('fcm open ', notification)
if (notification.data.obj_type == '1') {
this.props.navigation.navigate('ProductDetailPage', { prodId: notification.data.obj_id, })
} else {
this.props.navigation.navigate('SubCategoryPage', { catId: notification.data.obj_id, catName: 'Categories' })
}
})
});
My AppDelegate.h :
#import <UserNotifications/UserNotifications.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate>
#property (nonatomic, strong) UIWindow *window;
#end
My AppDelegate.m :
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#if __has_include(<React/RNSentry.h>)
#import <React/RNSentry.h> // This is used for versions of react >= 0.40
#else
#import "RNSentry.h" // This is used for versions of react < 0.40
#endif
#import "RNGoogleSignin.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <Firebase.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:#"reactenduser"
initialProperties:nil
launchOptions:launchOptions];
[RNSentry installWithRootView:rootView];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
// define UNUserNotificationCenter
[FIRApp configure];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
[RNFirebaseNotifications configure];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
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
]
|| [RNGoogleSignin application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation
];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[FBSDKAppEvents activateApp];
}
- (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) userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
[[RNFirebaseMessaging instance] didReceiveRemoteNotification:response.notification.request.content.userInfo];
completionHandler();
}
#end
I am not getting any data or error when i send the notification when my app goes to background. Only when it comes in foreground i can see the logs.
Any help would be appreciated. Thank you!

You need to turn on your background capabilities with for remote messages.
check the image
just a note, in my project I have background fetch, I think you can skip it.

Related

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 ios onNotification doesn't trigger

My project is importing 'react-native-firebase' and I'm trying sending test messages through firebase console using a device token. The method firebase.notifications().onNotification((notification)=>{}) triggers on android devices, but doesn't trigger on ios devices.
Notifications don't pop up both on foreground and background. I've tried 'console.log' in the method but doesn't present anything. please let me know what the problem is.
I tried 'onMessage()' but it triggers on foreground only.
here's my code:
if (Platform.OS == 'android') {
this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
console.log("onNotification");
console.log(notification);
notification
.setSound("default")
.android.setChannelId('default')
.android.setBigText(notification.body, notification.title, '')
// .android.setSmallIcon('#mipmap/icon_noti');
firebase.notifications().displayNotification(notification);
});
}
else {
this.notificationListener = firebase.notifications().onNotification((notification) => {
notification.setNotificationId(notification.messageId)
notification.setSound("default");
notification.setTitle(notification.data.title)
notification.ios.setBadge(notification.ios.badge ? notification.ios.badge + 1 : 0);
firebase.notifications().displayNotification(notification);
});
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 "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"
#import "RNSplashScreen.h"
#import Firebase;
#import UserNotifications;
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[GMSServices provideAPIKey:#"aasdfsafdadgadgadfasf"];
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:#"asdb"
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];
[FIRApp configure];
[RNFirebaseNotifications configure];
[RNSplashScreen show];
[[UIApplication sharedApplication] registerForRemoteNotifications];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
return YES;
}
- (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 didReceiveLocalNotification:(UILocalNotification *)notification {
[[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:#"main" withExtension:#"jsbundle"];
#endif
}
#end

How to fix apple push notifications recieved through firebase for react-native

I've configured for notification in iOS.
Generated certificate request locally and added apn to developer account.
Added the certificate to keychain access.
Configured and connected my firebase account in iOS using the package manager.
Added the Google-info.plist.
Did i miss any step in configuration. Also i followed the steps in react-native-firebase documentation for configuring for Cloud Messaging.
I've already followed the steps to configured the apn and firebase. including a step which has been missed by the rn-firebase documentation.
componentDidMount() {
this.messageListener = firebase.messaging().onMessage(message => {
// Process your message as required
Alert.alert('Notification',JSON.stringify(message))
console.info("Messaging ", message);
});
firebase.messaging().hasPermission().then(enabled => {
enabled ?
firebase.messaging().subscribeToTopic("testopic") :
firebase.messaging().requestPermission().then(enabledNow => {
enabledNow ?
firebase.messaging().subscribeToTopic("testopic") : '';
}).catch(err => {
Alert.alert('Notification', 'Enable notification to recieve attractive updates!')
});
})
// Background Notification handler
firebase.notifications().getInitialNotification()
.then((notificationOpen) => {
if (notificationOpen) {
// App was opened by a notification
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification = notificationOpen.notification;
}
});
this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification) => {
// Process your notification as required
// ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
});
this.notificationListener = firebase.notifications().onNotification((notification) => {
// Process your notification as required
Alert.alert('Notification',JSON.stringify(notification))
});
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification = notificationOpen.notification;
});
}
componentWillUnmount() {
this.notificationDisplayedListener();
this.notificationListener();
this.notificationOpenedListener();
}
Appdelegate.m File
#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <RNGoogleSignin/RNGoogleSignin.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <UserNotifications/UserNotifications.h>
#import <Firebase.h>
#import "RNFirebaseMessaging.h"
#import "RNFirebaseNotifications.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
[RNFirebaseNotifications configure];
NSURL *jsCodeLocation;
#ifdef DEBUG
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
#else
jsCodeLocation = [[NSBundle mainBundle] URLForResource:#"main" withExtension:#"jsbundle"];
#endif
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:#"customerapp"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
// Setup Notifications
if ([UNUserNotificationCenter class] != nil) {
// iOS 10 or later
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[FIRMessaging messaging].delegate = self;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (error) { NSLog(#"%#", error); }
}];
} else {
// iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerUserNotificationSettings:settings];
}
[application registerForRemoteNotifications];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
// return YES;
return [[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
}
// URL Scheme responder
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]]
|| [RNGoogleSignin application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
}
- (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)applicationDidBecomeActive:(UIApplication *)application {
[FBSDKAppEvents activateApp];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}
#end

error: missing context for method declaration with FB SDK on react native

I thought it would be easy to find similar issue but as fb haven't issues on their github, NO...
I strictly followed the instructions here: https://developers.facebook.com/docs/ios/getting-started
but it leverages this error which clearly indicate that what is after the #end is an issue. I understand that I'm declaring methods outside of the compiler scope but as FB isn't really full of information about this, I don't know what to do.
/Users/Jean/dev/mysuperapp/ios/mysuperapp/AppDelegate.m:82:1: error: missing context for method declaration
- (BOOL)application:(UIApplication *)application
^
/Users/Jean/dev/mysuperapp/ios/mysuperapp/AppDelegate.m:91:1: error: missing context for method declaration
- (BOOL)application:(UIApplication *)application
^
/Users/Jean/dev/mysuperapp/ios/mysuperapp/AppDelegate.m:106:1: error: missing context for method declaration
- (void)applicationDidBecomeActive:(UIApplication *)application {
^
3 errors generated.
I've found this similar issue which says that's because the code for FBSDK is after the #end which seems obvious. But if I move the code just before the #end the compiler complains about missing #end...
Missing context for method declaration
I'm sure it's just about understanding how the compiler works but I'm stuck on this one. I don't know Objective-C at all and I'm very confused with this error.
The entire file:
/**
* Copyright (c) 2015-present, Facebook, Inc.
* 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 <CodePush/CodePush.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "RNFIRMessaging.h"
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *jsCodeLocation;
#ifdef DEBUG
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
#else
jsCodeLocation = [CodePush bundleURL];
#endif
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:#"cupido"
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];
// Added for FCM
[FIRApp configure];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
return YES;
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
[RNFIRMessaging willPresentNotification:notification withCompletionHandler:completionHandler];
}
#if defined(__IPHONE_11_0)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
{
[RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
}
#else
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler
{
[RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
}
#endif
//You can skip this method if you don't want to use local notification
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[RNFIRMessaging didReceiveLocalNotification:notification];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[RNFIRMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
#end
// AppDelegate.m
#import <FBSDKCoreKit/FBSDKCoreKit.h>
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
// Add any custom logic here.
return YES;
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
];
// Add any custom logic here.
return handled;
}
// AppDelegate.m
#import <FBSDKCoreKit/FBSDKCoreKit.h>
- (void)applicationDidBecomeActive:(UIApplication *)application {
[FBSDKAppEvents activateApp];
}
Can you try like this?:
Code in the instructions should be put between #implementation AppDelegate and #end.
/**
* Copyright (c) 2015-present, Facebook, Inc.
* 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 <CodePush/CodePush.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "RNFIRMessaging.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *jsCodeLocation;
#ifdef DEBUG
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
#else
jsCodeLocation = [CodePush bundleURL];
#endif
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:#"cupido"
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];
// Added for FCM
[FIRApp configure];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
return YES;
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
[RNFIRMessaging willPresentNotification:notification withCompletionHandler:completionHandler];
}
#if defined(__IPHONE_11_0)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
{
[RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
}
#else
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler
{
[RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
}
#endif
//You can skip this method if you don't want to use local notification
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[RNFIRMessaging didReceiveLocalNotification:notification];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[RNFIRMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
];
// Add any custom logic here.
return handled;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[FBSDKAppEvents activateApp];
}
#end
The answer is the following. I thought I've already did something like this but it appears that I did it wrong. Now my app compiles.
/**
* Copyright (c) 2015-present, Facebook, Inc.
* 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 <CodePush/CodePush.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import "RNFIRMessaging.h" // FCM
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *jsCodeLocation;
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:#"index" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:#"cupidoIos"
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];
// Added for FCM
[FIRApp configure];
[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
return YES;
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
[RNFIRMessaging willPresentNotification:notification withCompletionHandler:completionHandler];
}
#if defined(__IPHONE_11_0)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
{
[RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
}
#else
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler
{
[RNFIRMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
}
#endif
//You can skip this method if you don't want to use local notification
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[RNFIRMessaging didReceiveLocalNotification:notification];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[RNFIRMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
- (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];
}
#end

Resources