Issue
Describe your issue here
Setup was completely done as per Firebase Instructions. I have integrated react native Firebase on my app and when I send a notification from Firebase console to Android app -> It triggers every time when the notification arrives irrespective of the App State, Works perfectly as expected. However when I do the same procedure from Firebase console to an iOS app it doesn’t trigger Message().onMessage
event. I tried it from Foreground, Background, Inactive states of the app, but of no use. I thought some one like @mikehardy @Salakar can help me in this regard, sorry to bother you guys.
Project Files
Javascript
import messaging from "@react-native-firebase/messaging"
import firestore from "@react-native-firebase/firestore"
import auth from "@react-native-firebase/auth"
import {Platform} from "react-native";
class FCMService {
register = (onRegister, onNotification, onOpenNotification) => {
this.checkPermission(onRegister)
this.createNotificationListeners(onRegister, onNotification, onOpenNotification)
}
registerAppWithFCM = async() => {
if (Platform.OS === "ios") {
await messaging().registerDeviceForRemoteMessages();
await messaging().setAutoInitEnabled(true)
}
}
sendTokenToServer = (token) => {
const notiRef = firestore()
.collection('noti')
.doc();
const uid = auth().currentUser.uid;
firestore()
.collection('noti')
.where('uid', '==', uid)
.get()
.then(querySnap => {
if (querySnap.empty) {
return notiRef.set({
_id: notiRef.id,
uid,
token
});
} else {
querySnap.forEach(doc => {
if (doc.exists) {
doc.ref.update({ token });
}
});
}
})
.catch(err => console.log('sendTokenToServer error : ', err));
};
checkPermission = (onRegister) => {
messaging().hasPermission()
.then(enabled => {
if (enabled) {
// User has permissions
this.getToken(onRegister)
} else {
// User doesn’t have permission
this.requestPermission(onRegister)
}
}).catch(error => {
console.log("[FCMService] Permission rejected ", error)
})
}
getToken = (onRegister) => {
messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
onRegister(fcmToken)
this.sendTokenToServer(fcmToken)
} else {
console.log("[FCMService] User does not have a device token")
}
}).catch(error => {
console.log("[FCMService] getToken rejected ", error)
})
}
requestPermission = (onRegister) => {
messaging().requestPermission()
.then(() => {
this.getToken(onRegister)
}).catch(error => {
console.log("[FCMService] Request Permission rejected ", error)
})
}
deleteToken = () => {
console.log("[FCMService] deleteToken ")
messaging().deleteToken()
.catch(error => {
console.log("[FCMService] Delete token error ", error)
})
}
createNotificationListeners = (onRegister, onNotification, onOpenNotification) => {
// When the application is running, but in the background
messaging()
.onNotificationOpenedApp(remoteMessage => {
console.log("[FCMService] onNotificationOpenedApp Notification caused app to open from background state:",remoteMessage)
if (remoteMessage) {
const notification = remoteMessage.notification
onOpenNotification(notification)
// this.removeDeliveredNotification(notification.notificationId)
}
});
// When the application is opened from a quit state.
messaging()
.getInitialNotification()
.then(remoteMessage => {
console.log("[FCMService] getInitialNotification Notification caused app to open from quit state:",remoteMessage)
if (remoteMessage) {
const notification = remoteMessage.notification
onOpenNotification(notification)
// this.removeDeliveredNotification(notification.notificationId)
}
});
// Foreground state messages
this.messageListener = messaging().onMessage(async remoteMessage => {
console.log("[FCMService] A new FCM message arrived!", remoteMessage);
if (remoteMessage) {
let notification = null
if (Platform.OS === "ios") {
notification = remoteMessage.data.notification
} else {
notification = remoteMessage.notification
}
onNotification(notification)
}
});
// Triggered when have new token
messaging().onTokenRefresh(fcmToken => {
console.log("[FCMService] New token refresh: ", fcmToken)
this.sendTokenToServer(fcmToken);
onRegister(fcmToken)
})
}
unRegister = () => {
this.messageListener()
}
}
export const fcmService = new FCMService()
fcmService.register(this.onRegister,this.onNotification,this.onOpenNotification);
this._notificationSubscription = messaging().onMessage(data => this._handleNotification(data));
package.json
:
“@react-native-firebase/app”: “^8.4.5”,
“@react-native-firebase/auth”: “^9.3.0”,
“@react-native-firebase/crashlytics”: “^8.4.12”,
“@react-native-firebase/database”: “^7.5.11”,
“@react-native-firebase/firestore”: “^7.8.6”,
“@react-native-firebase/messaging”: “^7.9.0”,
“@react-native-firebase/storage”: “^7.4.9”,
# N/A
firebase.json
for react-native-firebase v6:
# N/A
iOS
Click To Expand
ios/Podfile
:
- I’m not using Pods
- I’m using Pods and my Podfile looks like:
platform :ios, '10.0'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
target 'SovereignWallet' do
#use_frameworks!
# Pods for SovereignWallet
pod 'React', :path => '../node_modules/react-native/'
pod 'React-Core', :path => '../node_modules/react-native/React'
pod 'React-DevSupport', :path => '../node_modules/react-native/React'
pod 'React-fishhook', :path => '../node_modules/react-native/Libraries/fishhook'
pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
pod 'React-RCTWebSocket', :path => '../node_modules/react-native/Libraries/WebSocket'
pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
target 'SovereignWalletTests' do
inherit! :search_paths
# Pods for testing
end
use_native_modules!
end
target 'SovereignWallet-tvOS' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for SovereignTest1-tvOS
target 'SovereignWallet-tvOSTests' do
inherit! :search_paths
# Pods for testing
end
end
# N/A
AppDelegate.m
:
/**
- 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 <Firebase.h>
#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "RNSplashScreen.h"
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
[application registerForRemoteNotifications];
//Clear login data when
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:@"notFirstRun"]) {
[defaults setBool:YES forKey:@"notFirstRun"];
[defaults synchronize];
[[FIRAuth auth] signOut:NULL];
}
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"SovereignWallet"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:46.0f / 255.0f green:48.0f / 255.0f blue:50.0f / 255.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];
// Define UNUserNotificationCenter
UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
return YES;
}
// 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);
}
@end
Android
Click To Expand
Have you converted to AndroidX?
- my application is an AndroidX application?
- I am using
android/gradle.settings
jetifier=true
for Android compatibility? - I am using the NPM package
jetifier
for react-native compatibility?
android/build.gradle
:
// N/A
android/app/build.gradle
:
// N/A
android/settings.gradle
:
// N/A
MainApplication.java
:
// N/A
AndroidManifest.xml
:
<!-- N/A -->
Environment
Click To Expand
**System:
OS: macOS 10.15.7
CPU: (8) x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
Memory: 291.29 MB / 16.00 GB
Shell: 3.2.57 – /bin/bash
Binaries:
Node: 10.22.0 – ~/.nvm/versions/node/v10.22.0/bin/node
Yarn: 1.22.10 – /usr/local/bin/yarn
npm: 6.14.6 – ~/.nvm/versions/node/v10.22.0/bin/npm
Watchman: 4.9.0 – /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 14.0, DriverKit 19.0, macOS 10.15, tvOS 14.0, watchOS 7.0
Android SDK:
API Levels: 23, 28, 29
Build Tools: 23.0.1, 28.0.2, 28.0.3, 29.0.2
System Images: android-29 | Google APIs Intel x86 Atom, android-29 | Google Play Intel x86 Atom, android-30 | Google APIs Intel x86 Atom, android-30 | Google Play Intel x86 Atom
Android NDK: 21.1.6352462
IDEs:
Android Studio: 4.1 AI-201.8743.12.41.6858069
Xcode: 12.0.1/12A7300 – /usr/bin/xcodebuild
npmPackages:
react: 16.8.6 => 16.8.6 **
OUTPUT GOES HERE
- Platform that you’re experiencing the issue on:
- iOS
- Android
- iOS but have not tested behavior on Android
- Android but have not tested behavior on iOS
- Both
react-native-firebase
version you’re using that has this issue:
"@react-native-firebase/app": "^8.4.5",
"@react-native-firebase/auth": "^9.3.0",
"@react-native-firebase/crashlytics": "^8.4.12",
"@react-native-firebase/database": "^7.5.11",
"@react-native-firebase/firestore": "^7.8.6",
"@react-native-firebase/messaging": "^7.9.0",
"@react-native-firebase/storage": "^7.4.9",
- **`Firebase` module(s) you're using that h
```as the issue:**
- `e.g. Instance ID`
- **Are you using `TypeScript`?**
- `Y/N` & `VERSION`
</p>
</details>
<!-- Thanks for reading this far down ❤️ -->
<!-- High quality, detailed issues are much easier to triage for maintainers -->
<!-- For bonus points, if you put a 🔥 (:fire:) emojii at the start of the issue title we'll know -->
<!-- that you took the time to fill this out correctly, or, at least read this far -->
---
- 👉 Check out [`React Native Firebase`](https://twitter.com/rnfirebase) and [`Invertase`](https://twitter.com/invertaseio) on Twitter for updates on the library.
Resolved, Thanks for your help. It is GoogleService-info.plist file which was wrongfully pulled from the Firebase Console. Working in Foreground/Background/Quit App states.