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.
Related
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
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.
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
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.
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