EDIT (by @salakar): This is fixed since the 6.4.0 release.
Cloud messaging gives an error when using messaging().getToken
after upgrading to V6 and RN 0.61:
Error: [messaging/unknown] The operation couldn’t be completed. (com.firebase.iid error 1001.)
NativeFirebaseError: [messaging/unknown] The operation couldn’t be completed. (com.firebase.iid error 1001.)
at FirebaseMessagingModule.getToken (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:122099:28)
at _callee2$ (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:117856:74)
at tryCatch (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29289:19)
at Generator.invoke [as _invoke] (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29464:24)
at Generator.prototype.(anonymous function) [as next] (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29332:23)
at tryCatch (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29289:19)
at invoke (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29365:22)
at http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:29395:13
at tryCallTwo (http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false:3223:7
Click To Expand
#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like:
platform :ios, '9.0'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
target 'Glitz' do
use_native_modules!
# use_frameworks!
# Pods for Glitz
pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
pod 'React', :path => '../node_modules/react-native/'
pod 'React-Core', :path => '../node_modules/react-native/'
pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
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-Core/RCTWebSocket', :path => '../node_modules/react-native/'
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
# Pods for Glitz
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 'ReactCommon/jscallinvoker', :path => "../node_modules/react-native/ReactCommon"
pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
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'
pod 'react-native-ble-plx', :path => '../node_modules/react-native-ble-plx'
pod 'react-native-ble-plx-swift', :path => '../node_modules/react-native-ble-plx'
pod 'react-native-radar', :path => '../node_modules/react-native-radar'
# https://stackoverflow.com/questions/42021796/react-native-xcode-project-product-archive-fails-with-duplicate-symbols-for-arch
# https://github.com/facebook/react-native/issues/12814
pod 'react-native-ble-plx', :path => '../node_modules/react-native-ble-plx'
pod 'RNCPushNotificationIOS', :path => '../node_modules/@react-native-community/push-notification-ios'
post_install do |installer|
installer.pods_project.targets.each do |target|
targets_to_ignore = %w(React yoga)
if targets_to_ignore.include? target.name
target.remove_from_project
end
if target.name == 'react-native-ble-plx-swift'
target.build_configurations.each do |config|
config.build_settings['SWIFT_VERSION'] = '4.2'
end
end
if target.name == 'react-native-config'
phase = target.project.new(Xcodeproj::Project::Object::PBXShellScriptBuildPhase)
phase.shell_script = "cd ../../"\
" && RNC_ROOT=./node_modules/react-native-config/"\
" && export SYMROOT=$RNC_ROOT/ios/ReactNativeConfig"\
" && export BUILD_DIR=$RNC_ROOT/ios/ReactNativeConfig"\
" && ruby $RNC_ROOT/ios/ReactNativeConfig/BuildDotenvConfig.ruby"
target.build_phases << phase
target.build_phases.move(phase,0)
end
end
end
end
Click To Expand
#### Have you converted to AndroidX? - [x] my application is an AndroidX application? - [x] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility?
--- ## Environment**`react-native info` output:**
SDKs:
iOS SDK:
Platforms: iOS 13.0, DriverKit 19.0, macOS 10.15, tvOS 13.0, watchOS 6.0
Android SDK:
API Levels: 23, 25, 26, 27, 28
Build Tools: 27.0.3, 28.0.2, 28.0.3
System Images: android-26 | Intel x86 Atom_64, android-27 | Intel x86 Atom_64, android-27 | Google APIs Intel x86 Atom, android-28 | Google APIs Intel x86 Atom
IDEs:
Android Studio: 3.2 AI-181.5540.7.32.5056338
Xcode: 11.0/11A420a - /usr/bin/xcodebuild
npmPackages:
react: 16.9.0 => 16.9.0
react-native: 0.61.1 => 0.61.1
npmGlobalPackages:
create-react-native-app: 2.0.2
react-native-cli: 2.0.1
react-native-git-upgrade: 0.2.7
react-native-version: 3.1.0
- **Platform that you're experiencing the issue on**:
- [x] iOS
- [ ] Android
- [ ] **iOS** but have not tested behavior on Android
- [ ] **Android** but have not tested behavior on iOS
- [ ] Both
- **`react-native-firebase` version you're using that has this issue:**
- `6.0.0`
- **`Firebase` module(s) you're using that has the issue:**
- `Cloud messaging`
- **Are you using `TypeScript`?**
- `N`
I am also getting this error on RN 0.61.1 when I call await messaging().getToken();
.
For iOS, add the following in Info.plist:
"FirebaseAppDelegateProxyEnabled" set as "NO"
After this, I got the fcmToken.
cc @Salakar
Does this only happen on RN61? Is it fine on 60?
I just rolled back to a previous release branch for my app which had RN60.5 and I still get this error. cjishnu solution did not work me.
Is there maybe some logic missing that we have to do now before calling this function? I have read the docs but can't see anything obvious.
I managed to get a workaround for now. Since I am on iOS >= 12 requestPermission()
no longer prompts the user:
On iOS, messaging permission must be requested by the current application before messages can be received or sent.
On iOS >= 12, the app will be granted Provisional Authorization, and will resolve true. The user will be able to receive FCM payloads and Notifications immediately; but notifications will be displayed silently. The user, through Notification Center, then has the option of upgrading your apps notifications to no longer be silent.
So I use the PushNotificationIOS.requestPermissions()
from the @react-native-community/push-notification-ios
library to do this. Once the register
event has been triggered I can successfully call messaging().getToken()
which returns a token and no error.
For iOS, add the following in Info.plist:
"FirebaseAppDelegateProxyEnabled" set as "NO"
After this, I got the fcmToken.
I tried this workaround but got no lucky :( still got no token but error 1001
I just rolled back to a previous release branch for my app which had RN60.5 and I still get this error. cjishnu solution did not work me.
Is there maybe some logic missing that we have to do now before calling this function? I have read the docs but can't see anything obvious.
I managed to get a workaround for now. Since I am on iOS >= 12
requestPermission()
no longer prompts the user:On iOS, messaging permission must be requested by the current application before messages can be received or sent.
On iOS >= 12, the app will be granted Provisional Authorization, and will resolve true. The user will be able to receive FCM payloads and Notifications immediately; but notifications will be displayed silently. The user, through Notification Center, then has the option of upgrading your apps notifications to no longer be silent.
So I use the
PushNotificationIOS.requestPermissions()
from the@react-native-community/push-notification-ios
library to do this. Once theregister
event has been triggered I can successfully callmessaging().getToken()
which returns a token and no error.
I can confirm this is a temporary workaround for now.
I just rolled back to a previous release branch for my app which had RN60.5 and I still get this error. cjishnu solution did not work me.
Is there maybe some logic missing that we have to do now before calling this function? I have read the docs but can't see anything obvious.
I managed to get a workaround for now. Since I am on iOS >= 12
requestPermission()
no longer prompts the user:On iOS, messaging permission must be requested by the current application before messages can be received or sent.
On iOS >= 12, the app will be granted Provisional Authorization, and will resolve true. The user will be able to receive FCM payloads and Notifications immediately; but notifications will be displayed silently. The user, through Notification Center, then has the option of upgrading your apps notifications to no longer be silent.
So I use the
PushNotificationIOS.requestPermissions()
from the@react-native-community/push-notification-ios
library to do this. Once theregister
event has been triggered I can successfully callmessaging().getToken()
which returns a token and no error.
Does not work for me - register
event is not getting triggered. It stops the error from showing up though.. because getToken
is not getting called.
@AdamGold have you added the required methods to your AppDelegate.m file?
Finally, to enable support for notification and register events you need to augment your AppDelegate.
These methods can be found on the README on the repo.
@dwyery Yes, I have.
react-native-permissions is also pretty good...anyone tried that?
react-native-permissions is also pretty good...anyone tried that?
Yes, I can confirm that using react-native-permissions
is a workaround for now.
I'm doing the following with react-native-permissions
:
await requestNotifications(['alert', 'badge', 'sound']);
const instanceId = await iid().get();
const registrationToken = await messaging().getToken();
I'm getting the error the first time I run this code although the notification prompt is popping up and I'm confirming it. The second time (after reload) it's working.
I'm still getting an error after calling requestNotifications
with react-native-permissions
.
I think what worked for me was using react-native-permissions
to check and ask for notification permissions on iOS. I think it also helps to test this out on a physical device as simulators can't receive notifications.
@oskaryil Were you able to get the token in the simulator ?
This produces error when trying to get the token:
Permissions.requestNotifications(['alert', 'sound']).then(({ status, settings }) => {
console.log(status);
console.log(settings);
firebase.messaging().getToken()
.then(token => {
console.log(token);
})
})
It was working fine getting the token in simulator before upgrading firebase.
Using Xcode11 I was able to get it somewhat working on the device ( ios 13.1.2 ). When i use requestNotifications and get the permissions, first time the getToken is called i get the error
Error: [messaging/unknown] The operation couldn’t be completed. (com.firebase.iid error 1001.)
second time i click the button ( call the function to getToken ) it works and i get the token. Thats of course not ideal solution in any case, but at least it is somewhat working on the device. Any idea why it has to be triggered twice ?
Edit:
It seems that using the old solution on the device is working, just getting errors in the sim
firebase.messaging().requestPermission()
.then((value) => {
firebase.messaging().getToken()
.then(token => {
console.log(token);
})
})
Edit:
So it seems a bit random, i have to call it twice again to get token correctly even with the firebase.messaging().getToken()
Edit:
Also it seems to work fine on iOS 10 test device for me, so its probably related to iOS 13 more than anything else.
Actually I'm not sure whether I tested on a simulator (Xcode 11 / iOS 13) or my physical device 4 days ago (see my comment). However it looks like the error is not popping up on my iPhone 6 with iOS 12.4.2.
My code is:
let registrationToken = null;
const result = await requestNotifications(['alert', 'badge']);
if (result.status === RESULTS.GRANTED)
{
try
{
registrationToken = await messaging().getToken();
}
catch
{
console.log("Could not get registration token");
}
}
@leuchtdiode Yeah, i am pretty sure based on all the testing i did that its related to iOS 13 rather than to RNFirebase V6 or RN 0.61. It seems to be working fine on older iOS versions with both firebase.messaging().getToken() and React-Native-Permissions. Could work on V5 and iOS 13 tho, i did not test that.
We're trying to investigate a bit in relation to this and ios 13:
https://github.com/firebase/firebase-ios-sdk/issues/4011
That last comment is fascinating - could be unexpected behavior needing underlying SDK docs and maybe a mention in docs here - seems like it would affect v5 and v6 if you have default data collection disabled https://github.com/firebase/firebase-ios-sdk/issues/4011#issuecomment-539607761
and (linked off from there) possibly of interest https://onesignal.com/blog/ios-13-introduces-4-breaking-changes-to-notifications/
Well for what it's worth we didn't actively set any value in the info.plist (we don't have that field) so not sure if the default is off? Going to try a few combinations
Edit: still getting the error in ios 13 with FirebaseDataCollectionDefaultEnabled: YES in info.plist
Edit 2: As others said, second time loading it works. Very strange
I managed to get a workaround for now. Since I am on iOS >= 12
requestPermission()
no longer prompts the user:On iOS, messaging permission must be requested by the current application before messages can be received or sent.
On iOS >= 12, the app will be granted Provisional Authorization, and will resolve true. The user will be able to receive FCM payloads and Notifications immediately; but notifications will be displayed silently. The user, through Notification Center, then has the option of upgrading your apps notifications to no longer be silent.
Perhaps we should expand this to allow customising the behaviour for >= 12, it felt like a good idea at the time to use Provisional Authorization by default at the time, but now... not so much 🤷♂
@oskaryil Were you able to get the token in the simulator ?
This produces error when trying to get the token:
Permissions.requestNotifications(['alert', 'sound']).then(({ status, settings }) => { console.log(status); console.log(settings); firebase.messaging().getToken() .then(token => { console.log(token); }) })
It was working fine getting the token in simulator before upgrading
Nope, I'm still not able to get the token in the simulator, only on a physical device.
Getting that error when running in the simulator.
@oskaryil Were you able to get the token in the simulator ?
This produces error when trying to get the token:Permissions.requestNotifications(['alert', 'sound']).then(({ status, settings }) => { console.log(status); console.log(settings); firebase.messaging().getToken() .then(token => { console.log(token); }) })
It was working fine getting the token in simulator before upgrading
Nope, I'm still not able to get the token in the simulator, only on a physical device.
Getting that error when running in the simulator.
Maybe there was a change with Xcode 11 / iOS 13 as simluators can't receive notifications at all? Couldn't find any article/announcement though.
@oskaryil how does it work for you on the physical device with iOS 13 ? I have to call the getToken twice, because first time it always fails to retrieve the token, but second time it for some reason works. As far as i am concerned this is the main problem, the simulator is not as much important.
I am getting this error on physical devices with iOS 12 and 13.
@pierregoutheraud do you get it on the second time opening?
I am starting to believe I might have also been getting it on 12 (I updated my phone last night so cant test anymore) but that it went away on the second time which made me think it was gone
Here's a question I could do with thoughts on, should the permissions request be part of messaging
or should it just be documented to rely on another library like react-native-permissions
?
personally I think the ideal would be requestPermissions within messaging IF it doesn't have a huge surface area in terms of maintenance etc, otherwise if it does it probably makes more sense to offload the heavy lifting to react native permissions.
However I'm not 100% sure that is the root of this issue, as we also experience it using RN Permissions (I think others are too)?
Edit: the thing that seems consistent is that no matter the permission procedure (RN permissions or messaging library) it seems to resolve on second opening (correct me if youve had a different experience)
@SamMatthewsIsACommonName It's kind of random for me... I can not consistently reproduce this right now but I am getting error reports from users. And yes, I also experiment this using react-native-permissions
.
@Salakar I preferred the way it was implemented. Ie the permission request being part of messaging. That being said, with the iOS13 having silent notifications etc it seems like we should check for it in the app and ask for the updated permissions it seems, which would be out of scope of firebase.messaging. That would require something like react-native-permissions anyway.
I am just not realy sure how the iOS13 permissions for notifications should be handled. So far it worked well for iOS <= 12. So the question is basicaly if the iOS13 requires some special treatment as far as permissions goes.
@oskaryil how does it work for you on the physical device with iOS 13 ? I have to call the getToken twice, because first time it always fails to retrieve the token, but second time it for some reason works. As far as i am concerned this is the main problem, the simulator is not as much important.
@LukePenkava I can confirm this, I have the same issue. On the first boot after fresh install of the app I get the same error as shown in the screenshot I posted above. After reloading the app after having granted permission it works.
I find this weird because I am awaiting the permission check before trying to get the token.
My code looks like this (index.ts):
async componentDidMount() {
const {status} = await permissions.checkNotifications()
if (status === 'denied') {
await permissions.requestNotifications(['sound', 'badge'])
}
await this.getToken()
}
async getToken() {
const token = await messaging().getToken()
await axios.post(`${API_BASE_URL}/push/token`, {token})
}
We discussed internally earlier in the year about extending messaging permissions apis to work in a similar fashion to the built in RN ones; https://facebook.github.io/react-native/docs/pushnotificationios#requestpermissions - where you could be explicit about the types of permission you want to request and add support for additional ones to the options like iOS 12+ provisional
permissions.
Unfortunately it didn't make the v6 cut. Perhaps we can look at introducing this in a minor release somehow without breaking the existing methods (and look at deprecating them slowly).
I like the idea of messaging
not having to manage permissions, but I also like the idea of being able to install messaging
and go - without relying on another module. So I'm on the fence. 🤷♂
My guess is the following needs tweaking: https://github.com/invertase/react-native-firebase/blob/master/packages/messaging/ios/RNFBMessaging/RNFBMessagingModule.m#L139-L143 - perhaps someone can try removing the iOS 12 conditional locally and see how things go with this issue after that.
Additionally, try log out the error in this if
statement: https://github.com/invertase/react-native-firebase/blob/master/packages/messaging/ios/RNFBMessaging/RNFBMessagingModule.m#L92 - so we can see what the specific native error is.
@Salakar Having the permissions in messaging is definitely better, because you can always just not use it and use for example RNPermissions. So having them is one more option, which can in many cases be sufficient and make it much quicker. So as long its not a big deal to have them in messaging, it would perferable as it gives options. Thats at least my take on it.
@Salakar is that actually the reason for the error though? I've gone through and manually added all permissions etc and still had the error
edit: we'll try with the local logging of the error as you sugges
@Salakar is that actually the reason for the error though? I've gone through and manually added all permissions etc and still had the error
Don't think we know what the reason for the error is yet 😅 try add the logger at least, should give a better idea of whats up hopefully.
@Salakar
error is this:
Domain=com.firebase.iid Code=1001 "(null)"
Will try suggestions here:
https://stackoverflow.com/questions/38909670/firebase-fcm-failed-to-fetch-apns-token-error-domain-com-firebase-iid-code-100
@Salakar
error is this:Domain=com.firebase.iid Code=1001 "(null)"
Will try suggestions here:
stackoverflow.com/questions/38909670/firebase-fcm-failed-to-fetch-apns-token-error-domain-com-firebase-iid-code-100
& RCTLog(@"%@", [FIRMessaging messaging].APNSToken);
prints null.
@Salakar I did some debugging as well. Firstly i logged the stuff in simulator with iOS13 on 0.61.2.
The check for iOS version falls into the iOS12 check. I tried to remove the check and use the else part. That produces same error, but displays notification permission popup. Thats probably good, eventho i believe there was something said that iOS13 does not require permission to send silent notifications ?
Next thing i logged the error you mentioned, that throws this error in sim:
" 6.8.1 - [Firebase/Messaging][I-FCM012002] Error in application:didFailToRegisterForRemoteNotificationsWithError: remote notifications are not supported in the simulator"
So yeah, we cant probably get the token in sim because of this. Upon allowing notifications you get the error @SamMatthewsIsACommonName mentioned, thats stills same:
"Error = Error Domain=com.firebase.iid Code=1001 "(null)"
I also did debug it with my phone connected to Xcode. I noticed some log, not sure if its of any relevance:
6.8.1 - [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO. Follow the instructions at:
https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in_firebase_messaging
to ensure proper integration.
More interesting was when i had original code like this in RNFBMessagingModule.m, i would get the same error
if (@available(iOS 12.0, *)) {
NSLog(@"In 1");
authOptions = UNAuthorizationOptionProvisional | UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
} else {
NSLog(@"In 2");
authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
}
but changing it to this ( ie commenting out most of it )
/*if (@available(iOS 12.0, *)) {
NSLog(@"In 1");
authOptions = UNAuthorizationOptionProvisional | UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
} else {
NSLog(@"In 2");*/
authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
//}
it seems to work. I realy dont know what i am doing much, so i am not sure what might be the reason why it works now. I have tested it several times reinstalling the app and it always seems to work, but stops working once i uncomment the code. It would be good if someone else can test it as well to double check.
Edit: So basically it means the issue is the UNAuthorizationOptionProvisional in authOptions. By removing that conditional, the popup is there again instead of provisional authorization and it functions just like it did before. I am not sure if this is ok or not mostly for Apple Guidelines for iOS13 ? If its not a problem in that area, i am fine with the original functionality without provisional authorization.
Edit2: I have tested building the app to the device(iOS13) with this change, allowed notifications with popup ( on a first time ) and was able to receive notification from cloud function. So all good so far.
Did anyone resolve this? I've tried all above, but nothing works for me :(
Can someone please test the provided solution on physical device with iOS12 ? I had user report it not working on iOS12 ( iPhone 6 ).
@VanHop94 Did you try the fix i mentioned in the last post on physical device ? If so and its not working, can you provide some details ?
@Salakar Can you please confirm if this is a solution we can use ? Thank you
Edit: I have been able to successfully generate token on physical device with iOS10, iOS12 and iOS13 with 0.61.2
hello I am facing one problem in react-native0.60.5
@react-native-firebase/messaging
module that is
No task registered for key ReactNativeFirebaseMessagingHeadlessTask
it was working in react-native-firebase
I installed
@react-native-firebase/app (6.0.1)
@react-native-firebase/messaging (6.0.1)
@react-native-firebase/auth (6.0.1)
@react-native-firebase/firestore (6.0.1)
I added this line to MainApplication.java
import io.invertase.firebase.app.ReactNativeFirebaseAppPackage;
packages.add(new ReactNativeFirebaseAppPackage());
removed all service and receivers code from the android manifest file
my background task handler
import { firebase } from '@react-native-firebase/messaging';
import { ToastAndroid } from 'react-native';
import IntentLauncher, { IntentConstant } from 'react-native-intent-launcher';
export default async (message) => {
console.log('messaging');
console.log(message);
ToastAndroid.showWithGravityAndOffset('A wild toast appeared!', ToastAndroid.LONG, ToastAndroid.BOTTOM, 25, 50);
return Promise.resolve();
};
the headless code is running but couldn't call the headless task
it was working on react-native-firebase
i also tried adding thisline to manifiest
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
firestore is working fine, getting data updating data getting, adding data, realtime data
unlinked all the module as instructed in the new documentation
getting remote message when the app is open when the app is in the background but getting this error when the app is terminated
hello I am facing one problem in react-native0.60.5
@react-native-firebase/messaging
module that is
No task registered for key ReactNativeFirebaseMessagingHeadlessTask
it was working inreact-native-firebase
I installed
@react-native-firebase/app (6.0.1)
@react-native-firebase/messaging (6.0.1)
@react-native-firebase/auth (6.0.1)
@react-native-firebase/firestore (6.0.1)
I added this line to MainApplication.java
import io.invertase.firebase.app.ReactNativeFirebaseAppPackage; packages.add(new ReactNativeFirebaseAppPackage());
removed all service and receivers code from the android manifest file
my background task handler import { firebase } from '@react-native-firebase/messaging'; import { ToastAndroid } from 'react-native'; import IntentLauncher, { IntentConstant } from 'react-native-intent-launcher'; export default async (message) => { console.log('messaging'); console.log(message); ToastAndroid.showWithGravityAndOffset('A wild toast appeared!', ToastAndroid.LONG, ToastAndroid.BOTTOM, 25, 50); return Promise.resolve(); };
the headless code is running but couldn't call the headless task
it was working on react-native-firebasei also tried adding thisline to manifiest
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
firestore is working fine, getting data updating data getting, adding data, realtime data
unlinked all the module as instructed in the new documentation
getting remote message when the app is open when the app is in the background but getting this error when the app is terminated
i solved the problem all i had to is change the key name here
AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessaging);
i had to write ReactNativeFirebaseMessagingHeadlessTask instead RNFirebaseBackgroundMessage
but i have question who decide name of the key ? cant i make my own
@rizwan92 you are hijacking another issue with something separate - they key is static and defined for you it cannot change https://github.com/invertase/react-native-firebase/blob/master/packages/messaging/android/src/main/java/io/invertase/firebase/messaging/ReactNativeFirebaseMessagingHeadlessService.java#L15
Can someone please test the provided solution on physical device with iOS12 ? I had user report it not working on iOS12 ( iPhone 6 ).
@VanHop94 Did you try the fix i mentioned in the last post on physical device ? If so and its not working, can you provide some details ?
@Salakar Can you please confirm if this is a solution we can use ? Thank you
Edit: I have been able to successfully generate token on physical device with iOS10, iOS12 and iOS13 with 0.61.2
I've tried on simulator device but it doesn't work. We have to test on physical device?
Messaging does not work on iOS Simulators. They are not real devices, they do not have real tokens, they can not receive APNS messages (thus cannot receive FCM messages)
Messaging does not work on iOS Simulators. They are not real devices, they do not have real tokens, they can not receive APNS messages (thus cannot receive FCM messages)
Thank you so much. Let me try on real device
Messaging does not work on iOS Simulators. They are not real devices, they do not have real tokens, they can not receive APNS messages (thus cannot receive FCM messages)
Nevertheless, getToken
should not throw an exception when running on a simulator.
Is there anyone out there who has reliably got this working? I've tried everything suggested here but still just get a (com.firebase.iid error 1001.) error. I've requested permission every which way. This is on ios 13..
I've tried going back to RNF 5. but that seems to throw up a whole different set of issues.
Is there anyone out there who has reliably got this working? I've tried everything suggested here but still just get a (com.firebase.iid error 1001.) error. I've requested permission every which way. This is on ios 13._. I've tried going back to RNF 5._ but that seems to throw up a whole different set of issues.
Are you running it on a simulator or a real device?
Running it on a real device now.
Did you try the fix i tested? its working completely fine for me on iOS13 and iOS12 with 0.61.2 and RNFv6 ( on physical device ).
@LukePenkava no, no luck with your fix.
@paul-apacio As i mentioned, i am using latest RNF, RN 0.61.2, testing on physical device iPhone6(ios12) and XS(ios13), using xcode11. Then i just did this fix in RNFBMessagingModule.m:
if (@available(iOS 12.0, *)) {
NSLog(@"In 1");
authOptions = UNAuthorizationOptionProvisional | UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
} else {
NSLog(@"In 2");
authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
}
changed to
authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
and i am able to recieve token with this
requestNotificationPermission = () => {
firebase.messaging().hasPermission()
.then(enabled => {
if (enabled) {
console.log('has notification permission');
firebase.messaging().getToken()
.then(token => {
console.log(token);
})
.catch(error => console.log(error))
} else {
firebase.messaging().requestPermission()
.then((value) => {
console.log('Asking for notification permission');
firebase.messaging().getToken()
.then(token => {
console.log(token);
})
.catch(error => console.log(error))
})
.catch(error => console.log('rejected notification permission'));
}
})
.catch(error => console.log(error))
}
@LukePenkava I tried editting RNFBMessagingModule.m
as you said and I still get the error on getFcmToken()
(iOS 13.1.1)
I tried asking for permissions using messaging.requestPermission()
and using react-native-permissions
with requestNotifications(["alert"])
, both methods ends up with an error on getFcmToken()
.
There is one dirty thing that seems to fix/reduce the error which is waiting right after you ask for permissions (right before getFcmToken()
)
await requestNotifications(["alert"]);
await new Promise(resolve => setTimeout(resolve, 1000));
await getFcmToken()
Any solution?
The mentioned solutions here has not worked for me unfortunately. Anyone know if this is perhaps only in dev-mode or if it also occurs in release?
Edit: It works in release!
Can someone please post his/her AppDelegate configuration here for messaging? Since the v6 documentation still has a TODO I'm not sure if the error resides here.
I'm using react-native-permissions
and still get the error. However when I request the fcm token natively in my AppDelegate via
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instance ID: \(error)")
} else if let result = result {
print("Remote instance ID token: \(result.token)")
self.instanceIDTokenMessage.text = "Remote InstanceID token: \(result.token)"
}
}
it works and I get a token (after permission is given).
I have simply reverted to 5.x.x and all seems to be behaving now
this is fix now?
This seems like a bug somewhere in the lib - when I used this a while ago on iOS (native) I was able to get the fcmToken even before asking for push notification permissions.
Facebook also is doing something with this as you can see in the change log - some unrealesed changes and other fixes down the line.. https://github.com/firebase/firebase-ios-sdk/blob/e0b6d2347cce18ad3f64b0b4e29c0bf743e6af59/Firebase/InstanceID/CHANGELOG.md
I dont think we are using the newest Firebase SDK - are we sure that it is not already working with most recent lib?
I experience also issues with Crashlytics but I do get events logged in via analytics module.
I spent some time fixing this issue and want share my thoughts:
react-native-firebase
5.x.x and 6.x.x:getToken
calling [[FIRInstanceID instanceID] tokenWithAuthorizedEntity
getToken
was calling [FIRMessaging messaging] retrieveFCMTokenForSenderID
which was also calling inside [[FIRInstanceID instanceID] tokenWithAuthorizedEntity
as I understood the difference was a default scope passed to tokenWithAuthorizedEntity
I debugged code in Xcode to check what is failing; in my case error wast triggered in tokenWithAuthorizedEntity
method in ./ios/Pods//FirebaseInstanceID/Firebase/InstanceID/FIRInstanceID.m
in my case tokenWithAuthorizedEntity
was called twice: once on app init with scope='*' and second time when I call getToken
with scope=FCM
which triggered errorCode = kFIRInstanceIDErrorCodeMissingAPNSToken
so the solution for me was to check if APNSToken
is already available before calling getToken:
const apnToken = await messaging.getAPNSToken()
if (apnToken) {
const fcmToken = await messaging.getToken()
// send it to backend for push notification
}
If I understand correctly fcmToken
can be mapped to apnToken
or can be not; in second case users will not receive messages when app is not open; if you need fcmToken
for push notifications you need to be mapped;
finally, my observation was that you can get APN token when two condition match:
I tested the following:
firebase-admin
@delfrrr that appears to be fantastic work - @Salakar / @Ehesp I would expect this means a doc update in usage for token fetch in messaging but should also be added to steps for migration? This is one of the more popular issues I've seen in this repo it's clear it catches many out
@delfrrr It is not a fix though, right ? I still can't getAPNSToken()
or getToken()
the first time the app is launched.
@delfrrr It is not a fix though, right ? I still can't
getAPNSToken()
orgetToken()
the first time the app is launched.
I did not suggest a fix, I suggest way to debug: add breakpoints to this method in Xcode and see what happening; this method has ~10 different places where exception can be thrown; probably everyone in this topic has different issues, so there is no common answer/fix
@Salakar / @Ehesp the best solution would be if getToken
analyses error code and provides details
In my case I switched to implementation within the RNFBMessagingModule.m
in node_modules back to the way it was implemented in v5.x.. This is of course just a workaround but does it until this issue is officially fixed.
The getToken
method in RNFBMessagingModule.m
now looks like:
RCT_EXPORT_METHOD(getToken:
(NSString *) authorizedEntity
:(NSString *) scope
:(RCTPromiseResolveBlock) resolve
:(RCTPromiseRejectBlock) reject
) {
NSDictionary *options = nil;
if ([FIRMessaging messaging].APNSToken) {
options = @{@"apns_token": [FIRMessaging messaging].APNSToken};
}
[[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,
NSError * _Nullable error) {
if (error) {
[RNFBSharedUtils rejectPromiseWithNSError:reject error:error];
} else {
resolve(result.token);
}
}
This fixed it for me in any case. Also note that the official Firebase docs state:
Avoid calling .getToken(authorizedEntity,scope) unless there is a need to enable multiple senders. Use instanceIDWithHandler: instead.
Hey just to say that I use RNPermission with @AndroidGuyDD solution and it work for me on device on IOS12 & IOS13 ( add '}];' after the last else ).
Could temporarily workaround the issue to have notifications working with firebase 6 by doing 2 things :
react-native-permissions
to check and request notifications. react-native : 0.61.2
@react-native-firebase app and messaging : 6.0.1
react-native-permissions : 2.0.3
In RNFBMessagingModule.m:
[[FIRInstanceID instanceID] tokenWithAuthorizedEntity:authorizedEntity scope:scope options:options handler:^(NSString *_Nullable identity, NSError *_Nullable error) {
becomes:
[[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, NSError * _Nullable error) {
resolve(identity);
becomes:
resolve(result.token);
@rlemasquerier this works, thx!
Hi everybody, is patch for this problem released? And if not, are there any plans to do so, and when.
Thanks in advance :)
I have found a way to get rid of the error but it is kind of hacky.
The trick is to first request messaging().requestPermission();
because of this
The user will be able to receive FCM payloads and Notifications immediately; but notifications will be displayed silently"
And then call PushNotificationIOS.requestPermissions()
(before that you need to configure it on native side) from https://github.com/react-native-community/react-native-push-notification-ios
to get alert.
Like this:
async requestPermission() {
try {
await messaging().requestPermission();
return await PushNotificationIOS.requestPermissions();
} catch (error) {
console.log("permission rejected");
}
}
getToken working
Fortunately, I'm sending token to server after the user logged in. So I'm making the first request in componentDidMount (it return error), and the second request after user logged in, now we have the token.
Also I added import { requestNotifications } from 'react-native-permissions';
to request permission on application running, other way you will get muted notifications, until user not submit permissions in notifications panel on ios.
````
async componentDidMount() {
// Resolving bug with empty token on first getToken request
firebase.messaging().requestPermission()
.then((value) => {
firebase.messaging().getToken()
.then(token => {
console.log(token);
})
})
//Permissions request
await requestNotifications(['alert', 'badge', 'sound']);
}
````
Did any of you managed to get working push notifications on ios13?
any update on this? None of these hacks are working for us on 0.61.4
Well, @vpankov hack worked for me at RN ^0.61.4 (ios13+/android 28)
but dont use this react-native-permissions, instead i use the actual @react-native-community/push-notification-ios
to request and check permissions.
all works fine, the only problem i still have is not related to this.
Below snippet works for me
messaging().requestPermission().then(granted => {
granted && messaging().getToken().then(token => {
console.log('getToken', token);
});
});
@Salakar
Can we please get some update on this? It seems to be a bit all over the place. I have it for example working on ios13 iphoneXS and ios12.4 on iPhone6, but on iPhone5 on 10.3.4 its not possible to get the token whatever i try.
I had to implement the double request for requesting token ( sometimes it does not work on a first getToken request, but works on second one ). In my case also the manual hack helped in some cases in RNFBMessagingModule.m removing this check for authOptions
if (@available(iOS 12.0, *))
I am also able to get pretty much always through permissions, so it seems that permissions are not problem at all with
firebase.messaging().requestPermission()
but sometimes will get stuck on
firebase.messaging().getToken()
currently on iPhone5 with iOS 10.3.4 as mentioned before, but it seems that for some people it does not work at all.
Please look into this, so everyone does not have to have different hack to fix this. It would be great to get the token reliably on all devices. Thanks
Edit: Using RNF Messaging 6.0.3
Edit: I ended up using solution by AndroidGuyDD, that was only thing which fixed it for me on iPhone5. Still would be great to get some official update on this.
On my end, it seems to be working just fine on a real device. Simulator is the only place I get the error mentioned in OP.
This is using the following snippet:
messaging().requestPermission().then(granted => {
granted && messaging().getToken().then(token => {
console.log('token', token);
})
});
iOS simulators don't support push notifications and can't generate tokens (i'm pretty sure they are based on unique device ids so that makes sense).
We ended up switching to V6 for the android analytics support and had to convert this package as well. We essentially just use messages to receive the payloads from firebase..then have the background app push them into the tray as local notifications using react-native-push-notification
.
That allowed us to keep the backend setup that posts the messages to firebase in tact that we had when we used v5.
iOS simulators don't support push notifications and can't generate tokens (i'm pretty sure they are based on unique device ids so that makes sense).
Sorry, I should have mentioned that this is indeed working as expected 🤪
We ended up switching to V6 for the android analytics support and had to convert this package as well. We essentially just use messages to receive the payloads from firebase..then have the background app push them into the tray as local notifications using react-native-push-notification.
That allowed us to keep the backend setup that posts the messages to firebase in tact that we had when we used v5.
Interesting approach.
I found out that by delaying the getToken
call after requesting the error does not occur. We are playing it safe and doing a few second hack delay but it's resolved the issue for us!
*UPDATE: * this was somehow working for the past few hours and is now back to throwing the error, disregard this as a temporary solution.
Have fixed this in https://github.com/invertase/react-native-firebase/commit/8c339d10e288ef60e83e38bc4a245c5a251c83ff - the issue being that remote notification registration was still in progress (triggered internally by requestPermission
) when attempting to get a token - which is why it'd work when you delayed it or retried it. Have reproduced and can confirm it always returns the token now.
If you want to work around this before the v6.1.0 release then call the methods in the following order;
await messaging().registerForRemoteNotifications();
await messaging().requestPermission();
const token = await messaging().getToken();
The correct flow after the release is either of the following:
await messaging().registerForRemoteNotifications();
const token = await messaging().getToken();
await messaging().requestPermission();
const token = await messaging().getToken();
Will update docs to reflect.
@Salakar Unfortunately we are still receiving this warning after upgrading to v6.1.0
- Additionally we have tried both registerForRemoteNotifications
and requestPermission
on fresh installs and both immediately resolve to true without prompting the user for permission and when later checking if the permission is granted using react-native-permissions
it always returns denied. I'm sure we are doing something wrong on our end, any advice?
UPDATE: Everything works as expected when requesting the permissions using react-native-permissions
and then fetching the token using RNF getToken
method.
Please don't be offended if you're well past this, but I would make absolutely 100% sure you actually built the code you think you built by running npx react-native-clean-project clean-project-auto
. I have had release builds go out with stale parts from DerivedData until I learned (after wasting a lot of time...) to integrate that (or at least: most parts of the 'clean-project-auto' setting, via command-line switches to react-native-clean-project) into my release build process
@Salakar @mikehardy another issue i have faced is that i have updated from react-native-firebase:5.x.x
version to 6.1
.
If i run over previous app which is using react-native-firebase:5.x.x
still getting this error
The operation couldn’t be completed. (com.firebase.iid error 1001.)
if i run by uninstalling previous build then it generates the token.
The above thing is causing problems.
If i use @AndroidGuyDD provided solution then it worked.
Have fixed this in 8c339d1 - the issue being that remote notification registration was still in progress (triggered internally by
requestPermission
) when attempting to get a token - which is why it'd work when you delayed it or retried it. Have reproduced and can confirm it always returns the token now.If you want to work around this before the v6.1.0 release then call the methods in the following order;
await messaging().registerForRemoteNotifications(); await messaging().requestPermission(); const token = await messaging().getToken();
The correct flow after the release is either of the following:
await messaging().registerForRemoteNotifications(); const token = await messaging().getToken();
await messaging().requestPermission(); const token = await messaging().getToken();
Will update docs to reflect.
I tried it and it doesn't work. Yes, no error is given anymore, but sending silent notifications does not work.
Same here, I use 6.1.0 release too. Maybe it's me, maybe not.
As suggested by @Salakar I'm using
"@react-native-firebase/app": "^6.1.0",
"@react-native-firebase/messaging": "^6.1.0",
"react-native": "0.61.4",
const hasPermissions = await messaging().hasPermission()
let token
if (hasPermissions) {
await messaging().registerForRemoteNotifications()
token = await messaging().getToken()
} else {
const { status } = await requestNotifications(['alert', 'sound'])
if (status === 'granted') {
await messaging().registerForRemoteNotifications()
token = await messaging().getToken()
}
}
and still facing the issue. By delaying token = await messaging().getToken()
for a couple of seconds I'm able to get the token eventually.
no use.
Instead could we "Diff" other files/env/methods?
because may be some AppDelegate.m
config/import we are getting wrong..
@Salakar @mikehardy please reopen this issue as indeed it's not solved.
same issues, none of suggestions above worked.
Sure - I'm sorry I'm not involved in actually solving it, but reopening for attention is something I can definitely do
If I delete the app from my iPhone before running it in xCode it works. 🤷
It might be related to this https://github.com/firebase/firebase-ios-sdk/issues/2625
For me this issue only occurs on the Simulator in debug mode on version 6.0.2. I tried upgrading to 6.1.0 but any firebase.messaging()
functions would just kill the rest of the parent function without throwing any warnings or errors. Really weird. Perhaps I upgraded it wrong.
Honestly; I'm at a loss here on what to do 😞, I had it reproducible and made a fix, which caused it all to be working locally again for me, not sure what else to look at. Has anyone tried using patch-package
maybe to remove the provisional authorisation flag: https://github.com/invertase/react-native-firebase/blob/master/packages/messaging/ios/RNFBMessaging/RNFBMessagingModule.m#L150 (UNAuthorizationOptionProvisional
)
In the meantime, I'd suggest using react-native-permissions
for the time being to request permissions, as it seems using that doesn't cause issues?
@Salakar I'm using react-native-permissions
to request but still need to obtain the FCM token using getToken
. We are unfortunately still receiving the error.
As suggested by @Salakar I'm using
"@react-native-firebase/app": "^6.1.0", "@react-native-firebase/messaging": "^6.1.0", "react-native": "0.61.4",
const hasPermissions = await messaging().hasPermission() let token if (hasPermissions) { await messaging().registerForRemoteNotifications() token = await messaging().getToken() } else { const { status } = await requestNotifications(['alert', 'sound']) if (status === 'granted') { await messaging().registerForRemoteNotifications() token = await messaging().getToken() } }
and still facing the issue. By delaying
token = await messaging().getToken()
for a couple of seconds I'm able to get the token eventually.
This works for me. Thank you.
My code is as below.
import {requestNotifications} from "react-native-permissions";
const sleep = ms => {
return new Promise(resolve => setTimeout(resolve, ms));
};
const requestPermission = async () => {
try {
const permission = await requestNotifications(["alert", "badge", "sound"]);
if (permission.status === "granted") {
getFcmToken();
}
} catch (e) {}
};
const getFcmToken = () => {
try {
await requestNotifications(["alert", "badge", "sound"]);
await sleep(5000);
const fcmToken = await firebase.messaging().getToken();
//await handleToken(fcmToken);
} catch (e) {}
}
export const checkPermission = async () => {
try {
const enabled = await firebase.messaging().hasPermission();
if (enabled) {
getFcmToken();
} else {
requestPermission();
}
} catch (e) {}
};
I think I found a solution:
Make sure [FIRApp configure];
is the very first line in application didFinishLaunchingWithOptions
inside your AppDelegate.m
did you check whether your emulator has active internet or not?
Edit:
+1 Same issue
More info:
At the first time, i click "Build and then run the current scheme", i got token which printed in the Xcode Output Window. When stop app and reopen in the iphone, i got this problem
Log from Xcode for first time run:
2019-12-11 16:57:55.290 [info][tid:com.facebook.react.JavaScript] =====This registerForRemoteNotifications: true
2019-12-11 16:57:57.653 [info][tid:com.facebook.react.JavaScript] =====This granted notification permission: true
2019-12-11 16:57:57.663 [info][tid:com.facebook.react.JavaScript] 'User APNS Token: ', '2F547A612A4ADC13CB11A6CBEB866B4C5D3776F7A55C5AFD809FF30F0255151E'
2019-12-11 16:57:57.943 [info][tid:com.facebook.react.JavaScript] 'User FCM Token: ', 'fXY0ZOJymsA:APA91bGFWbiahnrwDJ0l6QgZbxxW1W9bABJ68cdi2uv8AiNrPzcNFobESEDZqy_xp4Dlgyc3yS0oxFl6B3ZHErLql0zjzPlh0g7tU4ZBRr7OdeWVIzY6UtQDT2WBTPY40WUeQ14SepeM'
My log i got when reopen app:
fbApp.SDK_VERSION: 6.2.0
=====This isRegisteredForRemoteNotifications: true
=====This registerForRemoteNotifications: true
=====This granted notification permission: true
User APNS Token: null
Possible Unhandled Promise Rejection (id: 0):
Error: [messaging/unknown] The operation couldn’t be completed. (com.firebase.iid error 1001.)
NativeFirebaseError: [messaging/unknown] The operation couldn’t be completed. (com.firebase.iid error 1001.)
at FirebaseMessagingModule.getToken (/Users/macos/Desktop/Project/ReactNative/Topica-uni/Sky500/.vscode/.react/index.bundle:123866:28)
at _callee$ (/Users/macos/Desktop/Project/ReactNative/Topica-uni/Sky500/.vscode/.react/index.bundle:190451:79)
at tryCatch (/Users/macos/Desktop/Project/ReactNative/Topica-uni/Sky500/.vscode/.react/index.bundle:29286:19)
at Generator.invoke [as _invoke] (/Users/macos/Desktop/Project/ReactNative/Topica-uni/Sky500/.vscode/.react/index.bundle:29461:24)
at Generator.prototype.(anonymous function) [as next] (/Users/macos/Desktop/Project/ReactNative/Topica-uni/Sky500/.vscode/.react/index.bundle:29329:23)
at tryCatch (/Users/macos/Desktop/Project/ReactNative/Topica-uni/Sky500/.vscode/.react/index.bundle:29286:19)
at invoke (/Users/macos/Desktop/Project/ReactNative/Topica-uni/Sky500/.vscode/.react/index.bundle:29362:22)
at /Users/macos/Desktop/Project/ReactNative/Topica-uni/Sky500/.vscode/.react/index.bundle:29372:15
at tryCallOne (/Users/macos/Desktop/Project/ReactNative/Topica-uni/Sky500/.vscode/.react/index.bundle:3240:14)
My code:
console.log(`fbApp.SDK_VERSION: ${fbApp.SDK_VERSION}`)
let userInfo = this.props.userInfo
//require Permission iOS
let isRegister = await fbMessaging.isRegisteredForRemoteNotifications
console.log(`=====This isRegisteredForRemoteNotifications: ${isRegister}`)
let regis = await fbMessaging.registerForRemoteNotifications()
console.log(`=====This registerForRemoteNotifications: ${regis}`)
let grant = await fbMessaging.requestPermission()
console.log(`=====This granted notification permission: ${grant}`)
if (!grant) {
return
}
const apnsToken = await fbMessaging.getAPNSToken()
console.log('User APNS Token: ', apnsToken)
const token = await fbMessaging.getToken()
console.log('User FCM Token: ', token)
My version react-native-firebase:
"@react-native-firebase/analytics": "^6.2.0",
"@react-native-firebase/app": "^6.2.0",
"@react-native-firebase/crashlytics": "^6.2.0",
"@react-native-firebase/iid": "^6.2.0",
"@react-native-firebase/messaging": "^6.2.0",
"@react-native-firebase/remote-config": "^6.2.0",
My IPhone6 OS Version: 11.4
The problem with the requestPermission
and registerForRemoteNotifications
in ios 12, is due to a bug in RNFBMessagingModule.m
.
In both the methods, this
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
should be called after [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions
as described in the documentation , where apple specifies:
Always call this method (requestAuthorizationWithOptions) before scheduling any local notifications and before registering with the Apple Push Notification service
I already tried in ios 12, and this change fixes the problem, and now I'm able to get the FCMToken (without using react-native-permissions as workaround)
@cark1 can you propose a PR with the code you have tested and are using? :pray:
Great. Thank you! What version will this make it into?
@CatalinVoss unknown, it is not even merged yet. However with 'patch-package' you can integrate known fixes for problems in a shared (between your team and CI etc) and consistent (it's in source control etc) way without waiting on release schedules. I use it all the time for things like this.
Thank you very much! Unfortunately the issue seems to persist for me even with the fix in the PR. Do some of the folks commenting above still have code in their AppDelegate.m
that communicates back to RNFirebaseMessaging? I do not, which is why I think the proposed plist change only makes things worse.
It seems that the first request goes through and provides me with a token, but subsequent calls to messaging().getToken()
all fail and even with the first logged token, push notifications are never delivered.
@CatalinVoss
Did you try putting [FIRApp configure];
as the very first line in application didFinishLaunchingWithOptions
inside your AppDelegate.m
?
Any luck or fix? I am also facing same issue. :(
Still no solution for this? :(
I am too so sad how to fix it ?
@tvhimanshu @AnkhHeart @ponleukea
Have you tried this solution from rlemasquerier. It worked with me.
Same issue, the operation couldn't be completed. (com.firebase.iid error 1001). Any solution?
react-native: 0.61.1
react-native-firebase: 6.2.0
These all look interesting as well - a good list of things to attempt https://stackoverflow.com/questions/38909670/firebase-fcm-failed-to-fetch-apns-token-error-domain-com-firebase-iid-code-100
I solve it without touching to native modules. You need to do 2 things. Request permission using react-native-permissions
. And add the following to Info.plist
<key>FirebaseAppDelegateProxyEnabled</key>
<string>NO</string>
you can notice the warning prints inside Xcode Debug, It tells you to add the above into Info.plist
Sample code:
import { firebase } from '@react-native-firebase/messaging'
import { requestNotifications } from 'react-native-permissions'
const waitFor = (ms) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, ms)
})
}
export const checkPermission = async () => {
try {
await requestNotifications(['alert', 'badge', 'sound'])
// Check permissions
const permissionGranted = await firebase.messaging().requestPermission()
if (permissionGranted) {
await firebase.messaging().registerForRemoteNotifications()
await waitFor(5000) // need to wait for `registerForRemoteNotifications` to finish
const fcmToken = await firebase.messaging().getToken()
console.log('TOKEN', fcmToken)
}
} catch (error) {
console.log(error)
}
}
checkPermission()
Hope this help
I can confirm that if I use an alternative permissions library (e.g. react-native-permissions
) to prompt the user and then manually wait for registerForRemoteNotification
to complete then I do not get the 1001 error. Running on device, iOS 13.3. Here is my code:
await requestNotifications(['alert', 'sound'])
// Check permissions
const permissionGranted = await messaging().requestPermission()
if (permissionGranted) {
await messaging().registerForRemoteNotifications()
console.log('REGISTERED')
// Manually wait
setTimeout(async () => {
const fcmToken = await messaging().getToken()
const apnsToken = await messaging().getAPNSToken()
console.log('TOKENS', fcmToken, apnsToken)
}, 5000)
} else {
console.log('FAILED TO REGISTER')
}
This would suggest that registerForRemoteNotification
is not waiting for the callback to complete before continuing thus causing an error when getToken
is called as we are still in the process of registering for notifications.
As far as I can tell there are two problems:
registerForRemoteNotification
not awaiting/calling back correctly. Potential fix: https://github.com/invertase/react-native-firebase/commit/8c339d10e288ef60e83e38bc4a245c5a251c83ffThis code is working fine.
import messaging from '@react-native-firebase/messaging';
import { requestNotifications } from 'react-native-permissions';
const registerForPushNotificationsAsync = async () => {
try {
await messaging().requestPermission();
await requestNotifications(['alert', 'badge', 'sound']);
const fcmToken = await messaging().getToken();
// Save
onTokenRefreshListenerRef.current = messaging().onTokenRefresh((token) => {
if (token) {
// Save
}
});
} catch (error) {
// Handle error
}
};
@345ml I get no error with your code but where are you calling registerForRemoteNotifications
? Isn't this required?
@alexfoxy
registerForRemoteNotifications
did not work.
I don't know why. . . .
So I use react-native-permissions
instead.
@345ml I think it is required? From the documentation:
On iOS, if your app wants to receive remote messages from FCM (via APNS), you must explicitly register this request with APNS. For example if you want to display alerts, play sounds or perform other user-facing actions (via the Notification library), you must call this method.
@alexfoxy
Thanks.
Indeed, that description in the documentation is a concern.
However, I uninstalled the app and tested it, but it seems that there is no problem in operation.
@345ml so you are receiving push notifications on the device ?
@alexfoxy
Yeah.
Get the token with messaging().getToken()
and it has been tested with Firebase console and Node.js AdminSDK.
This patch fixed this bug under my environment. Please merge.
https://github.com/rlemasquerier/pet-feeder/commit/898f378a4e3d9b0862ab4910cc685501600c2bde
@tughril that could be promising - if there is not an open PR for it could you make one, and if there is one could you link it here? That's how patches are proposed for merge
@tughril Your patch does the trick for me too - thanks!
I will make a PR now
Ok for the patch in my app with 6.2.0.
I just rolled back to a previous release branch for my app which had RN60.5 and I still get this error. cjishnu solution did not work me.
Is there maybe some logic missing that we have to do now before calling this function? I have read the docs but can't see anything obvious.
I managed to get a workaround for now. Since I am on iOS >= 12
requestPermission()
no longer prompts the user:On iOS, messaging permission must be requested by the current application before messages can be received or sent.
On iOS >= 12, the app will be granted Provisional Authorization, and will resolve true. The user will be able to receive FCM payloads and Notifications immediately; but notifications will be displayed silently. The user, through Notification Center, then has the option of upgrading your apps notifications to no longer be silent.
So I use the
PushNotificationIOS.requestPermissions()
from the@react-native-community/push-notification-ios
library to do this. Once theregister
event has been triggered I can successfully callmessaging().getToken()
which returns a token and no error.
Thanks for this. Helped me.
We worked around it with this-
Create a file, Workaround.m
in xcode. Paste the following
#import <Foundation/Foundation.h>
#import <React/RCTUtils.h>
#import <React/RCTConvert.h>
#import <React/RCTBridgeModule.h>
#import <Firebase/Firebase.h>
@interface Workaround: NSObject<RCTBridgeModule>
@end
@implementation Workaround
RCT_EXPORT_MODULE()
RCT_EXPORT_METHOD(getToken:(RCTPromiseResolveBlock) resolve:(RCTPromiseRejectBlock) reject) {
dispatch_async(dispatch_get_main_queue(), ^{
if ([UIApplication sharedApplication].isRegisteredForRemoteNotifications == NO) {
reject(@"error", @"error", nil);
return;
}
[[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, NSError * _Nullable error) {
if (error) {
reject(@"error", @"error", nil);
} else {
resolve(result.token);
}
}];
});
}
@end
Then replace getToken
calls with
import { Platform, NativeModules } from 'react-native'
if (Platform.OS === 'ios') {
NativeModules.Workaround.getToken()
} else {
messaging().getToken()
}
Sorry guys is there already a sort of time roadmap for this? It's important to understand if I would need to proceed with some proposed workaround or if we are close to an official fix.
Thanks!
+1
We worked around it with this-
Create a file,
Workaround.m
in xcode. Paste the following#import <Foundation/Foundation.h> #import <React/RCTUtils.h> #import <React/RCTConvert.h> #import <React/RCTBridgeModule.h> #import <Firebase/Firebase.h> @interface Workaround: NSObject<RCTBridgeModule> @end @implementation Workaround RCT_EXPORT_MODULE() RCT_EXPORT_METHOD(getToken:(RCTPromiseResolveBlock) resolve:(RCTPromiseRejectBlock) reject) { dispatch_async(dispatch_get_main_queue(), ^{ if ([UIApplication sharedApplication].isRegisteredForRemoteNotifications == NO) { reject(@"error", @"error", nil); return; } [[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result, NSError * _Nullable error) { if (error) { reject(@"error", @"error", nil); } else { resolve(result.token); } }]; }); } @end
Then replace
getToken
calls withimport { Platform, NativeModules } from 'react-native' if (Platform.OS === 'ios') { NativeModules.Workaround.getToken() } else { messaging().getToken() }
This solves the error but i can't seem to get an notification anymore :(
@kneza23 we use react-native-permissions to get permissions. You could try that! You need to call it before you call getToken, and check they granted permission
(Not sure about the iOS 12-style provisional push notifications though, as we don’t do that)
I created PR #3273 that should solve the root cause of the two issues that I think are causing most of the problems discussed here.
The native method registerForRemoteNotifications
is only really being called the first time the user calls it and only on the first boot of the app (on install).
This is because RNFirebase
implementation of registerForRemoteNotification
checks isRegisteredForRemoteNotifications
before calling the native method, and that returns true if the app is registered even if registerForRemotenotifications
has not been called yet for the current instance of the app. This makes sense, as when you register for remote notifications the first time after installing the app, the app should still be able to receive remote notifications even if you kill it or restart it later.
However, not calling registerForRemoteNotification
again on app start is an issue for RNFirebase because it depends on [FIRMessaging messaging].APNSToken
being set, and that is only done on the call back after successful registration, so currently what happens is that upon starting the app (when it is not the first boot) the APNSToken
stays null always.
There is also a race condition when trying to access the APNSToken
in some native methods, as both RNFirebase
and the FirebaseMessaging
libraries are "swizziling" the AppDelegate methods for didRegisterForRemoteNotifications
with token, and only the FirebaseMessaging
library is setting the value for [FIRMessaging messaging].APNSToken
. In my testing I noticed that the RNFirebase
swizzled methods are called first, and it might cause the promise to be resolved before the APNSToken is set.
Well, I want to start by highlighting that requesting permissions is not needed for registering for remote notifications as long as you don't want to show the user alert notifications. There is a strong use case for remote notifications without alerts, as this functionality powers A/B testing, remote config in firebase, as well as it can be used by the apps for internal functionality. Additionally, you might want to get the remote notifications token as early as possible, but defer asking the user the permissions until you can. The provisional permission added in iOS 12 and which is used in RNFirebase
tries to fix this, but only if the users are on iOS12 or greater, so if you want to target older operating systems you wouldn't want to ask for permissions on boot as this is commonly recognized as a bad practice. Again, requesting permissions doesn't solve the underlying issue, and I still experienced problems with it.
Removing the "provisional" permission from the request (or requesting permissions with other libraries), as is suggested in some of the solutions, does seem to resolve some of the race conditions, but only because when the permission request dialog is shown to the user there is a delay while waiting for the user to approve it, and that seems to be enough in some cases to solve the race condition. However, if the user is really fast, you can still experience issues (it happened to me while testing if I immediately pressed accept).
Technically this happens because requestPermission
in RNFirebase
is internally calling register for remote notifications, and after that is successful it request the permission from the user. This gives it enough time to get the APNS token before proceeding. But, again, in my tests using iOS 12 this only works on first boot.
This also seems to work because the delay of asking it twice fixes the race condition in some cases. However, it doesn't always works. And still doesn't work for successive boots of the app were the APNSToken
will still be null.
Some have reported success adding a delay after calling registerForRemoteNotifications
before calling getToken
. This works on first boot just because it seems to solve the race condition, however the time of the delay varies highly depending on the network conditions, as some devices might register really fast and others take longer.
The current work around by changing [[FIRInstanceID instanceID] tokenWithAuthorizedEntity]
with [[FIRInstanceID instanceID] instanceIDWithHandler]
in the getToken
method avoids the promise rejection because the second method does not require the APNSToken
being set to resolve successfully. However it removes functionality from the API as you can't longer pass an authorizedEntity
or scope
to get a token (this is, however, not used a lot and there is a lot of missing documentation even in the native libraries about how to use this parameters).
However, this still doesn't work if you want to get the APNStoken
, because it will always return null in successive boots of the app as registerForRemoteNotifications
won't be called.
Check PR #3273 to see the full description of the solution, but what it basically does is:
RNFBMessagingAppDelegateInterceptor
to set [FIRMessaging messaging].APNSToken
. This is what the FIRMessagingRemoteNotificationsProxy
in FirebaseMessaging
does, and doing it here seems to avoid the race condition. It doesn't do any damage anyway to do it here first anyway.registerForRemoteNotifications
in RNFirebase
to skip the check for isRegisteredForRemoteNotifications
. This avoids the APNSToken being null when calling getTokens, and it should be left to the programmer to decide when to call this method.I only have an iOS 12 device, so this solution might not work for everybody and will require some additional testing from the community. However, from my analysis I think it should work on all cases, or at least it should fix some of the cases and don't affect anything else.
@Salakar and @mikehardy, can you please check this? I think PR #3273 should supersede #3130, as it is a definitive fix instead of a work around.
@kneza23 we use react-native-permissions to get permissions. You could try that! You need to call it before you call getToken, and check they granted permission
(Not sure about the iOS 12-style provisional push notifications though, as we don’t do that)
it is not a problem with requesting a permission dialog (i also use react-native-permissions) it is just that there is no notification received on the device after i allow the notifications on the permission alert.
it's now 5 month, can we expect a fix soon?
any updates?
@arthedza The fixed proposed by @elyalvarado is being worked on and should be merged soon. Check https://github.com/invertase/react-native-firebase/pull/3273 for the progress on it.
I tried all of the above but it didn't work. Does the fix include in v6.3.4?
I also try with "@react-native-firebase/messaging": "6.4.0-rc0"
but still the same
NativeFirebaseError: [messaging/unknown] no valid “aps-environment” entitlement string found for application
at FirebaseMessagingModule.requestPermission (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:164729:28)
at registerForPushNotificationsAsync$ (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:159780:77)
at tryCatch (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25461:19)
at Generator.invoke [as _invoke] (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25637:24)
at Generator.prototype.<computed> [as next] (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25504:23)
at tryCatch (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25461:19)
at invoke (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25537:22)
at http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25567:13
at tryCallTwo (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:26826:7)
@dgana that's an issue with your Firebase credential details connecting with FCM/APNS:
@Ehesp Thanks a lot for replying, I already did what you ask to check the bundle ID and APN certificate on the firebase console. I cleaned the project and rebuild again but still does not work
NativeFirebaseError: [messaging/unknown] no valid “aps-environment” entitlement string found for application
at FirebaseMessagingModule.requestPermission (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:164729:28)
at registerForPushNotificationsAsync$ (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:159780:77)
at tryCatch (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25461:19)
at Generator.invoke [as _invoke] (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25637:24)
at Generator.prototype.<computed> [as next] (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25504:23)
at tryCatch (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25461:19)
at invoke (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25537:22)
at http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:25567:13
at tryCallTwo (http://192.168.0.187:8081/index.bundle?platform=ios&dev=true&minify=false:26826:7)
This is my code
import messaging from '@react-native-firebase/messaging';
import {requestNotifications} from 'react-native-permissions';
...
React.useEffect(() => {
const registerForPushNotificationsAsync = async () => {
try {
await messaging().requestPermission();
await requestNotifications(['alert', 'badge', 'sound']);
const fcmToken = await messaging().getToken();
console.log(fcmToken);
} catch (error) {
console.log(error);
}
};
if (Platform.OS === 'ios') {
registerForPushNotificationsAsync();
}
}, []);
...
package.json
"react": "16.9.0",
"react-native": "0.61.5",
"@react-native-firebase/messaging": "^6.3.4",
"react-native-permissions": "^2.0.10"
But my push notification for android works very well
const {getItem} = useAsyncStorage('userToken');
const writeDatabase = React.useCallback(
async fcmToken => {
const idUser = await getItem();
await database()
.ref(`${idUser}/fcm_token`)
.set(fcmToken);
},
[getItem],
);
React.useEffect(() => {
notificationManager.configure(
onRegister,
onNotification,
onOpenNotification,
SENDER_ID,
);
}, [onRegister]);
const onRegister = React.useCallback(token => writeDatabase(token), [
writeDatabase,
]);
const onNotification = notify => {
console.log('[Notification] onNotification ', notify);
};
const onOpenNotification = notify => {
console.log('[Notification] onOpenNotification ', notify);
};
NotificationManager.js
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
import {Platform} from 'react-native';
class NotificationManager {
configure = (onRegister, onNotification, onOpenNotification, senderId) => {
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
onRegister(token.token);
console.log('[NotificationManager] onRegister Token:', token.token);
},
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log('[NotificationManager] onNotification:', notification);
if (Platform.OS === 'ios') {
if (notification.data.openedInForeground) {
notification.userInteraction = true;
}
}
if (notification.userInteraction) {
onOpenNotification(notification);
} else {
onNotification(notification);
}
if (Platform.OS === 'android') {
notification.userInteraction = true;
}
// Only call callback if not from foreground
if (Platform.OS === 'ios') {
if (!notification.data.openedInForeground) {
notification.finish(PushNotificationIOS.FetchResult.NoData);
}
} else {
notification.finish(PushNotificationIOS.FetchResult.NoData);
}
},
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: true,
senderID: senderId,
});
};
buildAndroidNotification = (id, title, message, data = {}, options = {}) => {
return {
id,
autoCancel: true,
largeIcon: options.largeIcon || 'ic_launcher',
smallIcon: options.smallIcon || 'ic_launcher',
bigText: message || '',
subText: title || '',
vibrate: options.vibrate || false,
vibration: options.vibration || 300,
priority: options.priority || 'high',
importance: options.importance || 'high',
data,
};
};
buildIOSNotification = (id, title, message, data = {}, options = {}) => {
return {
alertAction: options.alertAction || 'view',
category: options.category || '',
userInfo: {
id,
item: data,
},
};
};
showNotification = (id, title, message, data = {}, options = {}) => {
PushNotification.localNotification({
/* Android Only Properties */
...this.buildAndroidNotification(id, title, message, data, options),
/* IOS Only Properties */
...this.buildIOSNotification(id, title, message, data, options),
/* IOS and Android Properties */
title: title || '',
message: message || '',
playSound: options.playSound || false,
soundName: options.soundName || 'default',
userInteraction: false, // If the notification was opened by the user from the notification area or not
});
};
cancelAllLocalNotification = () => {
if (Platform.OS === 'ios') {
PushNotificationIOS.removeAllDeliveredNotifications();
} else {
PushNotification.cancelAllLocalNotifications();
}
};
unregister = () => {
PushNotification.unregister();
};
}
export const notificationManager = new NotificationManager();
I got this also when i already removed the react-native-permissions library and clean the project
Message from Xcode
2020-03-20 18:38:56.311 [error][tid:com.facebook.react.JavaScript] Error: react-native-permissions: NativeModule.RNPermissions is null. To fix this issue try these steps:
• If you are using CocoaPods on iOS, run `pod install` in the `ios` directory and then rebuild and re-run the app. You may also need to re-open Xcode to get the new pods.
* If you are getting this error while unit testing you need to mock the native module. Follow the guide in the README.
If none of these fix the issue, please open an issue on the Github repository: https://github.com/react-native-community/react-native-permissions
I just want to ask does react-native-permissions required for "@react-native-firebase/messaging": "^6.3.4"
?
Yeah permissions are required to receive messages (even if they don't display a notification).
So there is no permanent solution?
@dgana It looks like the issue you're experiencing is because you need the push notifications entitlement in your app. Make sure you have the required entitlement assigned to your target. At least in iOS If you're not going to display "remote notifications" to the user you don't need the permission, but you'll only be able to use silent-notifications.
@elyalvarado currently I have the exact same issue as #3292. When I call messaging().registerForRemoteNotifications(), it never resolves. messaging().getAPNSToken() returns nil token. Do you have any solution for this? Thank you
React.useEffect(() => {
const registerForPushNotificationsAsync = async () => {
try {
if (!messaging().isRegisteredForRemoteNotifications) {
await messaging().registerForRemoteNotifications();
}
const fcmToken = await messaging().getToken();
console.log('FCM TOKEN ', fcmToken);
} catch (error) {
console.log(error);
}
};
if (Platform.OS === 'ios') {
registerForPushNotificationsAsync();
}
}, []);
FCM Token never gets called but if i take out registerForRemoteNotifications the error message should call the registerForRemoteNotifications() or requestPermission()
@dgana That is fixed in #3273 which is not yet released. You can work around it by using patch-package
to patch your current @react-native-firebase/messaging
version, until a new version is released including the fix.
As for your code, having a conditional around registerForRemoteNotifications
to check isRegisteredForRemoteNotifications
will always cause the getAPNSToken
call to be null after the first time the app boots and therefore registers. This is because isRegisteredForRemoteNotifications
is persisted across different app starts, but the APNs token is only assigned when calling registerForRemoteNotifications
and is not persisted across boots. If you remove the conditional getAPNSToken
should work again.
@elyalvarado i have use the patch package but it seems i got no luck. the console.log('Goes here') doesn't get called at all. Sorry to bother you but idont understand swift code i need help and i'm still new. The problem is just i can't resolve messaging().registerForRemoteNotifications()
or the messaging().requestPermission()
React.useEffect(() => {
const registerNotificationIOS = async () => {
try {
await messaging().registerForRemoteNotifications();
console.log('Goes here');
const fcmToken = await messaging().getToken();
console.log('FCM TOKEN ', fcmToken);
} catch (error) {
console.log(error);
}
};
if (Platform.OS === 'ios') {
registerNotificationIOS();
}
}, []);
patches/@react-native-firebase+messaging+6.3.4.patch
diff --git a/node_modules/@react-native-firebase/messaging/ios/RNFBMessaging/RNFBMessagingAppDelegateInterceptor.m b/node_modules/@react-native-firebase/messaging/ios/RNFBMessaging/RNFBMessagingAppDelegateInterceptor.m
index c2150a5..60f6083 100644
--- a/node_modules/@react-native-firebase/messaging/ios/RNFBMessaging/RNFBMessagingAppDelegateInterceptor.m
+++ b/node_modules/@react-native-firebase/messaging/ios/RNFBMessaging/RNFBMessagingAppDelegateInterceptor.m
@@ -44,6 +44,7 @@ - (void)setPromiseResolve:(RCTPromiseResolveBlock)resolve andPromiseReject:(RCTP
// called when `registerForRemoteNotifications` completes successfully
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
+ [FIRMessaging messaging].APNSToken = deviceToken;
if (_registerPromiseResolver != nil) {
_registerPromiseResolver(@([RCTConvert BOOL:@([UIApplication sharedApplication].isRegisteredForRemoteNotifications)]));
_registerPromiseResolver = nil;
diff --git a/node_modules/@react-native-firebase/messaging/ios/RNFBMessaging/RNFBMessagingModule.m b/node_modules/@react-native-firebase/messaging/ios/RNFBMessaging/RNFBMessagingModule.m
index 89f1d4a..102d3db 100644
--- a/node_modules/@react-native-firebase/messaging/ios/RNFBMessaging/RNFBMessagingModule.m
+++ b/node_modules/@react-native-firebase/messaging/ios/RNFBMessaging/RNFBMessagingModule.m
@@ -181,10 +181,6 @@ - (NSDictionary *)constantsToExport {
(RCTPromiseResolveBlock) resolve
: (RCTPromiseRejectBlock) reject
) {
- if ([UIApplication sharedApplication].isRegisteredForRemoteNotifications == YES) {
- return resolve(@([RCTConvert BOOL:@(YES)]));
- }
-
[[RNFBMessagingAppDelegateInterceptor sharedInstance] setPromiseResolve:resolve andPromiseReject:reject];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
Hello @dgana, It worked when the 'FirebaseAppDelegateProxyEnabled: NO' setting was deleted.
Dependencies:
"@react-native-firebase/app": "6.4.0-rc0",
"@react-native-firebase/messaging": "6.4.0-rc0"
My Code:
import React, { Component } from 'react';
import firebase from '@react-native-firebase/app';
import '@react-native-firebase/messaging';
export default class App extends Component {
componentDidMount() {
try {
await firebase.messaging().registerForRemoteNotifications();
await firebase.messaging().requestPermission();
} catch(e) {
console.error(e);
}
try {
firebase.messaging().onMessage(this.onNotification);
firebase.messaging().onTokenRefresh(this.register);
await firebase.messaging().getToken().then(this.register);
}
catch(e) {
console.error(e);
}
}
onNotification(args) {
...
}
register(token) {
...
}
render() {
return (
...
);
}
}
Yes it works! Thank you @abdurrahmanekr @elyalvarado @Ehesp
'FirebaseAppDelegateProxyEnabled: NO'
setting deleted resolve the issue for promise not resolving and patch-package
. But still I have my problem in not unchecking the automatically manage signing in and have to download provisioning profile manually in Singing & Capabilities in Xcode. create provisioning profile from developer.apple.com and create new provision.
FYI i tried rebulding again with 'FirebaseAppDelegateProxyEnabled: NO'
in my Info.plist and it does not resolve the promise in messaging().registerForRemoteNotifications()
. So it's important to note to remove the 'FirebaseAppDelegateProxyEnabled: NO'
in Info.plist.
My iphone device now receive the notification even when its locked! Thanks!
Yeah so we discovered yesterday there is all sorts of problems with messaging on iOS, which are also in v5. We'll have a new version out in the coming days which provides a better integration with permissions (customisable) & also fixes a bunch of issues with reregistering the device with FCM. There's currently a race condition in native land which we solved which can cause weird behaviour.
In general though; make sure Push Notifications & Remote Messages are enabled via XCode.
Apple also throttle pretty badly too which is causing us a headache for testing. Very annoying.
react-native: 0.61.5
react-native-firebase: V6
const requestPermission = async()=> {
const {uid} = props;
try {
const ref = firestore().collection('users').doc(`${uid}`);
await firebase.messaging().registerForRemoteNotifications();
const granted = firebase.messaging().requestPermission();
if (granted) {
const apnsToken = await firebase.messaging().getToken();
ref.set({ apnsToken: apnsToken },{merge:true});
} else {
console.log('User declined messaging permissions :(');
}
} catch (e) {
console.log(e.message);
}
}
[messaging/unknown] The operation couldn’t be completed. (com.firebase.iid error 1001.)
I just rolled back to a previous release branch for my app which had RN60.5 and I still get this error. cjishnu solution did not work me.
Is there maybe some logic missing that we have to do now before calling this function? I have read the docs but can't see anything obvious.
I managed to get a workaround for now. Since I am on iOS >= 12
requestPermission()
no longer prompts the user:On iOS, messaging permission must be requested by the current application before messages can be received or sent.
On iOS >= 12, the app will be granted Provisional Authorization, and will resolve true. The user will be able to receive FCM payloads and Notifications immediately; but notifications will be displayed silently. The user, through Notification Center, then has the option of upgrading your apps notifications to no longer be silent.
So I use the
PushNotificationIOS.requestPermissions()
from the@react-native-community/push-notification-ios
library to do this. Once theregister
event has been triggered I can successfully callmessaging().getToken()
which returns a token and no error.
It worked for me :)
@elyalvarado What is patch-package
? How do I get it ?
@elyalvarado https://github.com/ds300/patch-package
FYI after updating Xcode to the current version right now 11.4 you have to create the APN key again in developer.apple.com
PR #3339 which fixes this issue and many others has now been merged and is also available on an RC release (6.4.0-rc4) - please check it out, see PR description for all the fixes & improvements to messaging - there's a ton!
Thank you all for participating in this issue and for all those that posted workarounds.
package.json
"@react-native-firebase/app": "6.4.0-rc4",
"@react-native-firebase/auth": "6.4.0-rc4",
"@react-native-firebase/database": "6.4.0-rc4",
"@react-native-firebase/firestore": "6.4.0-rc4",
"@react-native-firebase/messaging": "6.4.0-rc4",
My code
/**
* Trigger iOS only device to register for remote
* notification and save it to Firestore
*/
React.useEffect(() => {
const registerNotificationIOS = async () => {
try {
const granted = await messaging().registerDeviceForRemoteMessages();
if (granted) {
const fcmToken = await messaging().getToken();
console.log('FCM TOKEN ', fcmToken);
writeFirestore(fcmToken);
}
} catch (error) {
console.log(error);
}
};
if (Platform.OS === 'ios') {
registerNotificationIOS();
}
// eslint-disable-next-line
}, []);
It works very good in 6.4.0-rc4 without the patches anymore from patch-package and always resolves FCM token. But it doesn't trigger onOpenNotification function when i tap it from react-native-push-notification lib that i use and notification doesn't receive when app is in foreground. Any ideas why @Salakar ? Maybe i'm missing something. Thank you for the new version!
The messaging and react native push notifications library are separate libraries. Messages handles message payloads from fcm and that's it. It has no impact on any notifications you create from that lib.
As for why it only works in the background, that's how FCM handles it via the native SDKs, we don't control that.
Thank you for the reply @Ehesp Noted
this issue is still occurring with me i can not retrieve token in ios in fresh react-native installation.
Environment:
this issue is still occurring with me i can not retrieve token in ios in fresh react-native installation.
Environment:
- react-native: 0.60.2
- "@react-native-firebase/app": "^6.3.4",
- "@react-native-firebase/messaging": "^6.3.4",
The fix will be applied in v6.4.0 as far as I understand. You are using 6.3.4.
this issue is still occurring with me i can not retrieve token in ios in fresh react-native installation.
Environment:
- react-native: 0.60.2
- "@react-native-firebase/app": "^6.3.4",
- "@react-native-firebase/messaging": "^6.3.4",
Upgrade verions with those;
"@react-native-firebase/app": "6.4.0-rc4",
"@react-native-firebase/messaging": "6.4.0-rc4",
Thank you for the reply @leuchtdiode,@bsonmez Noted :)
I got the notifications working remotely in iOS 13.4 and the library works great! as of right now just follow the documentation in https://rnfb-docs.netlify.com/messaging
. My problem right now it's just the delayed notifications sometimes for about 15 minutes. But after i received the first notification, the next one is fast just about 1 - 2 seconds. No problem if I send 15 - 20 notification after that it works fast. The next try if I wait 3 hour and send again from the server it takes lot of time to wait. As of my understanding after iOS 13 you have to send apns headers also.
reference:
https://aws.amazon.com/blogs/messaging-and-targeting/sending-push-notifications-to-ios-13-and-watchos-6-devices/
https://developer.apple.com/videos/play/wwdc2019/707/?time=799
https://firebase.google.com/docs/cloud-messaging/http-server-ref
Anyone experiencing this issue maybe?
My index.js code using firebase cloud function
reference: https://firebase.google.com/docs/reference/admin/node/admin.messaging.MulticastMessage
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const message = {
data: {...},
notification: {
title,
body,
},
android: {
priority,
data: {...},
notification: {
title,
body,
sound,
priority,
},
},
apns: {
headers: {
'apns-push-type': 'alert',
'apns-priority': '10',
'apns-topic': BUNDLE_ID,
},
payload: {
aps: {
alert: {
title,
body,
},
sound,
contentAvailable: true,
},
},
},
tokens: ARRAY_OF_FCM_TOKEN,
};
const response = await admin.messaging().sendMulticast(message);
console.log(response)
package.json
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.0"
"react": "16.9.0",
"react-native": "0.61.5",
"@react-native-community/push-notification-ios": "^1.1.0",
"@react-native-firebase/app": "6.4.0-rc4",
"@react-native-firebase/auth": "6.4.0-rc4",
"@react-native-firebase/database": "6.4.0-rc4",
"@react-native-firebase/firestore": "6.4.0-rc4",
"@react-native-firebase/messaging": "6.4.0-rc4",
"react-native-push-notification": "^3.1.9",
If you integrate with react-native-push-notification
set the contentAvailable true
for the listeners to run as of my understanding.
v6.4.0 is now live, as is the new docs that covers this https://rnfirebase.io/messaging/usage
@dgana iOS can & will throttle (or even drop) notifications if you send too many, the Apple docs I believe suggest up to 2-3 pushes an hour that contain the content-available
flag, so only use content-available
where you need to know about a notification being received (content-available
is not required for notification press events, so you'll still know when a user interacts with one of your remote notifications) or if it has data e.g. for building local notifications, if you need to send more than this for visual alerts use remote notifications without content-available
, I covered the behaviour of content-available
in all the various scenarios here: https://github.com/invertase/react-native-firebase/issues/3367#issuecomment-607368063
I also added a mini guide on how you can see throttle events in your device logs: https://github.com/invertase/react-native-firebase/issues/3367#issuecomment-607391532
@Salakar thanks for the update. Will there be a patch fix for v5 as well? I am currently on v5 and unable to upgrade currently.
There is no way to backport all the fixes for messaging that went in to v6 to v5, they were massive and v5 has been on life support only for months and months. I understand (as a v5 user currently) that the prospect of upgrading something so fundamental is daunting, but it's about time. Notifee has iOS support in testing now (developed in conjunction with those fixes) and there are other libraries as well
Just updated to 6.4.0
Now getting the following error on Android:
NativeFirebaseError: [messaging/unknown] FIS_AUTH_ERROR
Coming from await getToken()
method
Hello,
after upgrading to v6.4.0, I can't send messages to iOS devices from Firebase.
I use the following to retrieve a token (same statement as with v5.x):
const token = await firebase.messaging().getToken()
When trying to send a remote message from Firebase, it gives me this error:
Auth error from APNS or Web Push Service
Any ideas? Do I have to set a scope or authorizedEntity?
did you do firebase.messaging().requestPermission()
and firebase.messaging().registerDeviceForRemoteMessages()
?
Yes. In my case it is used for data messages only in a (weak) 2Factor Auth Scenario:
await firebase.messaging().registerDeviceForRemoteMessages()
await firebase.messaging().requestPermission()
const token = await firebase.messaging().getToken()
...
Requesting permissions shouldn't even be necessary for my use case. All the above functions work. But the serverside complains when trying to send a message and no message handler gets fired. That's why I'm wondering if in v5 a different default scope or authorizedEntity was used.
By data messages
you mean silent push?
As far as I understand you should call the firebase.messaging().requestPermission()
first.
Regarding the message handler - share the code that is not working for you.
What I do usually when testing is getting apns token and try to send push witha different service - you can easily find a tool or python script that would do that. Then you can rule out at least push notification setup on iOS part.
Exactly, it's a silent push. The message handle part should not be concerned as the error happens on the server side.
Nevertheless here you go:
useEffect(() => {
async function registerNotification() {
await firebase.messaging().registerDeviceForRemoteMessages()
await firebase.messaging().requestPermission()
const token = await firebase.messaging().getToken()
...
}
const cleanup = firebase.messaging().onMessage(message => {
const { data } = message
...
})
registerNotification()
return cleanup
}, [])
Did you try to send push notification without firebase?
If error is on server side are you sure you should be looking here for resolution? How do you send the push? Via firebase cloud messaging platform directly or API?
Well, it's working with v5.x and it stops working when trying to upgrade to v6.4. For sure the error could be in my implementation, but so far I could not find a working solution. Thanks a lot for your help, I'll get back if I get more insights
v6.7.1 still get null
when calling getAPNSToken
Same for me on server -
I am running on v 6.7.1 and I also get the:
Error: [messaging/unknown] SERVICE_NOT_AVAILABLE
NativeFirebaseError: [messaging/unknown] SERVICE_NOT_AVAILABLE
As soon as I try to get the token on Android.
Same issue on "@react-native-firebase/app": "^7.1.4", "@react-native-firebase/messaging": "^7.1.3", "react-native": "0.62.2". Any solution to fix it?
Check your internet connection. May be little help
I am running on v 7.2.0 for app and v 7.1.4 for messaging and I also get the:
Error: [messaging/unknown] SERVICE_NOT_AVAILABLE
NativeFirebaseError: [messaging/unknown] SERVICE_NOT_AVAILABLE
As soon as I try to get the token on Android.
I am still having this issue in iOS. Please help if there is any escape?
I downgrade for app v 6.7.1 and messaging v 6.7.1 and work
@RaulCorreia I am already using 6.7.1 and it was working fine by last week but today when I ran again. It alerts me same error.
Any other solution or escape?
@RaulCorreia I am already using 6.7.1 and it was working fine by last week but today when I ran again. It alerts me same error.
Any other solution or escape?
What I did was, generate another google-services.json in the firebase panel and use version 6.7.1 and it worked again.
I don't know if what I did really changed anything, but it was the only thing I did.
@RaulCorreia I am having the same issue with the latest version of @react-native-firebase/app and @react-native-firebase/messaging. When I try to get device token with messaging.getToken(), it returns this error:
Error: [messaging/unknown] SERVICE_NOT_AVAILABLE
NativeFirebaseError: [messaging/unknown] SERVICE_NOT_AVAILABLE
Has anyone solved a similar problem recently? @luvnish19 how did you solve the problem on your end?
Any help will be appreciated here
@BoluwajiDavids
I am using version 6.7.1 and I removed and add .p8 file on console.developers.google.com fixed my issue.
Thank you @luvnish19
I am building for android.
I have downgraded to 6.7.1 for both @react-native-firebase/app and @react-native-firebase/messaging previously but still had the same problem. I don't know if the p8 file you mentioned applies to android too?
@RaulCorreia I am already using 6.7.1 and it was working fine by last week but today when I ran again. It alerts me same error.
Any other solution or escape?What I did was, generate another google-services.json in the firebase panel and use version 6.7.1 and it worked again.
I don't know if what I did really changed anything, but it was the only thing I did.
thanks alot it worked for me. changed only google services.json file
"react-native": "0.61.5",
"@react-native-firebase/messaging": "^6.3.4"
await firebase.messaging().registerForRemoteNotifications();
const granted = firebase.messaging().requestPermission();
Facing this issue:
[messaging/unknown] The operation couldn’t be completed. (com.firebase.iid error 1001.)
The same issue +1
Most helpful comment
We worked around it with this-
Create a file,
Workaround.m
in xcode. Paste the followingThen replace
getToken
calls with