Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IOS unable to receive notification #1203

Closed
PratikG9 opened this issue Jun 11, 2018 · 48 comments
Closed

IOS unable to receive notification #1203

PratikG9 opened this issue Jun 11, 2018 · 48 comments

Comments

@PratikG9
Copy link

PratikG9 commented Jun 11, 2018

Issue:
Not able to receive notification on iOS device

What I've tried:
I've followed this documentation to implement notifications in iOS,
https://rnfirebase.io/docs/v4.2.x/notifications/ios

iOS implementation:
AppDelegate.m

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"

@import Firebase;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{  
  /// Firebase configuration
  [FIRApp configure];
  [RNFirebaseNotifications configure];
  
  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"XYZApp"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
  [[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
  [[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
  [[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}

@end

Application's Home File

componentDidMount() {
      /// get permission and reuest FCM token
      this.notificationRequestPermission()

      /// Triggered when a particular notification has been displayed
      this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification) => {
          // Process your notification as required
          // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
          console.log("NOTIFICATION DISPLAYED", notification)
      });

      /// Triggered when a particular notification has been received
      this.notificationListener = firebase.notifications().onNotification((notificationobj) => {
          // Process your notification as required
          console.log("NOTIFICATION RECEIVED", notificationobj)               
      });

      /// Listen for a notification being opened
      
      // Foreground or Background
      this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
        // Get the action triggered by the notification being opened
      });

      // App closed
      firebase.notifications().getInitialNotification()
      .then((notificationOpen) => {
        if (notificationOpen) {
          // App was opened by a notification
        }
      });
}

Can somebody guide me in this, is there any other implementation way to receive notification in iOS

@TimMun
Copy link

TimMun commented Jun 12, 2018

I think I have a similar problem except my messages are showing up, but in the wrong context. I have both remote Messaging and Notifications enabled, yet when I send a Notification+Data message from the FCM Console, the message is received on firebase.messaging().onMessage() instead of in firebase.notifications().onNotification(). From the docs it seems like messages from FCM console should be handled by the Notifications module, but they're actually be handled by the Messaging module.

With that in mind, have you tried following the instructions in the Cloud Messaging setup, i.e. listen with firebase.messaging().onMessage() and seeing if your notification pops up there instead?

@PratikG9
Copy link
Author

@TimMun thanks for the suggestion

Yes I've tried with firebase.messaging().onMessage() and able to get message. but as per the documentation it should be used in case of data messages only. and how can I get notification when app is closed with onMessage().

there is one more thing I'd like to mention, my delegate methods are not calling.

@chriswang101
Copy link

chriswang101 commented Jun 12, 2018

It appears as if RNFirebase documentation is missing a few required steps. After adding the below code after [RNFirebaseNotifications configure]; in AppDelegate.m, remote notifications worked for me.

// Setup Notifications
  if ([UNUserNotificationCenter class] != nil) {
    // iOS 10 or later
    // For iOS 10 display notification (sent via APNS)
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
    UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
    [FIRMessaging messaging].delegate = self;
    [[UNUserNotificationCenter currentNotificationCenter]
     requestAuthorizationWithOptions:authOptions
     completionHandler:^(BOOL granted, NSError * _Nullable error) {
       if (error) { NSLog(@"%@", error); }
     }];
  } else {
    // iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [application registerUserNotificationSettings:settings];
  }
[application registerForRemoteNotifications];

Make sure to add the required import or else your code won't compile
#import <UserNotifications/UserNotifications.h>

@TimMun
Copy link

TimMun commented Jun 13, 2018

Can confirm this worked for me, now notifications sent from FCM composer are coming thru on notifications().onNotification(). Thanks!

@chrisbianca
Copy link
Contributor

As per the documentation, this block of code is handled by the requestPermission method: https://rnfirebase.io/docs/v4.2.x/notifications/receiving-notifications#2)-Request-permissions

@yarian
Copy link

yarian commented Aug 15, 2018

@chrisbianca Can you please clarify something, we just spent days debugging this issue and I think I just understood the source of it and a way to avoid future confusion.

We were experiencing notifications from our app not arriving, not even when calling APNS directly using the APNS token. (Although, only for some users). We were not calling firebase.messaging().requestPermission();. We realized this and we added the call, but like so:

 return firebase
      .messaging()
      .hasPermission()
      .then(enabled => {
        if (!enabled) {
          firebase
            .messaging()
            .requestPermission()
            .then(() => {
              this._initializeListeners()
              Tracking.track('User just granted notifications')
            })
            .catch(() => {
              Tracking.track('User denied notifications')
            })
        }
      })

We still had reports of some people not receiving them. When we (almost by accident) added code similar to chriswang's above they started working for those people.

So I have a few questions/points I'd like to raise.

  1. Where does requestPermission register for notifications? Here?
  2. Is it required that we call requestPermission? If so, how often? (Every time APNs token might have changed?) The current docs make it sound like it's optional, only if you're having permissions issues. For example: (emphasis mine)

If the user has not already granted permissions, then you can prompt them to do so, as follows:

Before you are able to send and receive Notifications, you need to ensure that the user has granted the correct permissions:

The second example above is slightly misleading, because it's not true that we just have to ensure they granted permissions, we have to do it by calling a specific react-native-firebase method that does more than just that.

  1. If I'm understanding right, and requestPermission also registers for notifications, I would like to suggest that that is separated unto its own thing to make it much more explicit.

Instead of having docs that suggest you do:

firebase.messaging().requestPermission()
  .then(() => {
    // User has authorised  
  })
  .catch(error => {
    // User has rejected permissions  
  });

Have the default instructions be:

firebase.messaging().requestPermission()
  .then(() => {
    firebase.messaging().registerForNotifications()
  })
  .catch(error => {
    // User has rejected permissions  
  });

That way it's clear, even if you're somehow getting a permissions dialog without adding this code, that you still have to register for notifications.

@sanjcho
Copy link

sanjcho commented Sep 18, 2018

Hi everyone!
Encountered a similar problem and all of this suggestions don't work for me. Solved by setting FirebaseAppDelegateProxyEnabled to yes in info.plist and reinstalling app on test iPhone. Hope it helps somebody.

@malangaveuday
Copy link

@chriswang101
Thank you, man
Your solution worked for me

@Bloueco
Copy link

Bloueco commented Jan 17, 2019

Worked for me too man. Thanks @sanjcho !!!!!

@faustoct1
Copy link

still not working for me.. does have any config on AppDelegate.m ?!?

@Sunrise17
Copy link

When i delete and reinstall the app, FCM Console sending notification through fcmToken, however when i stop and run the code again, iOS device stopped receiving notification from Console. I have also added FirebaseAppDelegateProxyEnabled (yes) in info.plist. However issue has not been solved yet. I am planning to add cloud function to send notification, but even console has such reliability issue how i will go on?

@MinaFSedrak
Copy link

MinaFSedrak commented Mar 12, 2019

It's working ONLY while testing for a specific Fcm Token... not working while publishing a campaign (for all users). Any updates !????

@jsuryahyd
Copy link

jsuryahyd commented Mar 18, 2019

It worked for me when I used firebase.messaging.onMessage() listener, but only on foreground. cannot get notifications in background and when app is closed.
Also, the notification object inside the listener is different to that of android i.e the notificationId key is not present in ios notification. So, while building notification, I had to pass .setNotificationId(nO._messageId), otherwise the display function throws error.

@evanjmg
Copy link

evanjmg commented Apr 7, 2019

@yarian thank you so much - For everyone not receiving pushes - request Permission is required even if you have pushes already enabled!! I am migrating a swift app to react native and wasn't receiving pushes even though I had the token. Just calling requestPermission fixed it.

@fabiodamasceno
Copy link

fabiodamasceno commented Apr 10, 2019

Tried with latest react-native and firebase version, worked for me with @evanjmg tip. Anyone still have this issue? If not we can close It.

@whalemare
Copy link

whalemare commented Apr 10, 2019

@fabiodamasceno yes, I am still have the same issue on react-native=0.59.3 and react-native-firebase=5.2.5.
Doing all from answers above for solve this problem, but nothing happens.
On iOS I can receive notification only in firebase.messaging().onMessage(/** here **/)function, and only in simulator. On real devices pushes was not received.

Trying send all of json combinations of both notification and data (only data, only notification, and both together):

notification: {
  title: data.subject,
  body: data.text
},
data: {
  title: data.subject,
  body: data.text
}

@yusuf987
Copy link

FirebaseAppDelegateProxyEnabled

i am not able to fine FirebaseAppDelegateProxyEnabled in my info.plist,
should i add it and set it to true ?
or there is something else wrong with my project

@fardeen-panjwani
Copy link

fardeen-panjwani commented May 22, 2019

It appears as if RNFirebase documentation is missing a few required steps. After adding the below code after [RNFirebaseNotifications configure]; in AppDelegate.m, remote notifications worked for me.

// Setup Notifications
  if ([UNUserNotificationCenter class] != nil) {
    // iOS 10 or later
    // For iOS 10 display notification (sent via APNS)
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
    UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
    [FIRMessaging messaging].delegate = self;
    [[UNUserNotificationCenter currentNotificationCenter]
     requestAuthorizationWithOptions:authOptions
     completionHandler:^(BOOL granted, NSError * _Nullable error) {
       if (error) { NSLog(@"%@", error); }
     }];
  } else {
    // iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [application registerUserNotificationSettings:settings];
  }
[application registerForRemoteNotifications];

Make sure to add the required import or else your code won't compile
#import <UserNotifications/UserNotifications.h>

Can you please upload the full AppDelegate.m file or point me to a full-fledged walkthrough of the steps that you went through? Thant would be a huge help because my AppDelegate.m file looks a lot different that the one's I've seen on this thread. Thanks!

@chriswang101
Copy link

Oof sorry it's been a year since I wrote that code and I no longer have access to the app's AppDelegate.m file. I do recall that the above code was the only significant change I made to the file. Otherwise, it was just a default AppDelegate file.

@mikehardy
Copy link
Collaborator

I just tested my app both with and without those changes. Those changes are not necessary. Per the install docs, you need this:

  • you need the correct pods installed and configured and react-native-firebase must be linked correctly, and maybe clean ios build / restart xcode because...xcode
  • [RNFirebaseNotifications configure]; after [FIRApp configure];
  • you need to requestPermission (and receive it...)
  • if you are subscribing to a topic or something, you need to do this after you have a token (do it in the "I got a token" branches of getToken/onTokenRefresh (this tripped me up for a moment)
  • you need to listen to all the right handlers (you'll want onMessage here

You do not need to add the AppDelegateProxy = true plist entry, if you watch your debug messages in XCode you'll notice that's the default

You do not need to add that big chunk of AppDelegate code, if you trace the react-native-firebase iOS code, you'll notice it does all that stuff already

Then send a message and it should work. I just did this with the 5.3.x versions and pods 5.20.2 on iOS 9 even and it works

My message send script looks like this, and I am receiving them reliably:

curl -X POST \
--header "Authorization: key=$SERVER_KEY"  \
--Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"/topics/AppInfo\",\"collapse_key\": \"AppInfo\",\"content_available\": true, \"priority\": \"high\", \"data\":{\"task\":\"CheckVersion\"}}"

@Pradeepchauhan89
Copy link

It appears as if RNFirebase documentation is missing a few required steps. After adding the below code after [RNFirebaseNotifications configure]; in AppDelegate.m, remote notifications worked for me.

// Setup Notifications
  if ([UNUserNotificationCenter class] != nil) {
    // iOS 10 or later
    // For iOS 10 display notification (sent via APNS)
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
    UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
    [FIRMessaging messaging].delegate = self;
    [[UNUserNotificationCenter currentNotificationCenter]
     requestAuthorizationWithOptions:authOptions
     completionHandler:^(BOOL granted, NSError * _Nullable error) {
       if (error) { NSLog(@"%@", error); }
     }];
  } else {
    // iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [application registerUserNotificationSettings:settings];
  }
[application registerForRemoteNotifications];

Make sure to add the required import or else your code won't compile
#import <UserNotifications/UserNotifications.h>

Thanks man.

it works

@fabiodamasceno
Copy link

@whalemare can you share your AppDelegate.m and code that you add to your solution, maybe the problem could be clarified :D.

People, what do you think about send a PR with this improvement to documentation?

@mikehardy
Copy link
Collaborator

I'm on record with my opinion of the suggestions here, sorry #1203 (comment)

None of it is or should be necessary if things are installed correctly, on current versions. I have tested it, it works as currently documented

I'm working on a demo here to back that assertion but just haven't got messaging demonstrated yet. If someone wants to beat me to it, you just need a public repo with messaging integrated as documented - if you can demonstrate a sample app installed as documented that doesn't work, then definitely we'll change docs but I'll be surprised...

@Kevinpahlevi
Copy link

any follow up for this? try all above but still not help my problem
its seems weird even i try install old version get same problem, i remember old version still can recieve notifications

@sam17896
Copy link

sam17896 commented Jul 8, 2019

tried everything but in vein, my firebase console says that it has send around 200 notifications in last 90 days but none received on IOS, android is fine, is the docs not clear or is there issue with the library? Its frustrating.

@sam17896
Copy link

sam17896 commented Jul 8, 2019

For those who are still facing this, please make sure that you have push notification service key created in your developer account of apple, and upload this key with key id and team id to your firebase app in firebase console. For complete setup follow this video -> https://www.youtube.com/watch?v=zeW8DO5KZ8Q

@TimMun
Copy link

TimMun commented Aug 13, 2019

I spent a few days digging into this. I think the reason there are so many varying reports as to what works and what doesn’t is due in part to a few factors: 1.) not calling requestPermission; 2.) FCM token is not updated correctly; 3.) iOS and APNS throttling; and 4.) testing conditions. (All this is relevant to iOS only)

  1. As pointed out elsewhere and in various other threads regarding why messages/notifications don’t work: you need to call firebase.messaging().requestPermission(), even if hasPermission() says they’re already granted. chriswang’s solution above (putting that block of code in AppDelegate.m) basically does the same thing as requestPermission (in fact, see RNFirebaseMessaging.m, method requestPermission() ); it works because it’s executing similar code as requestPermission every time your app starts up. For me, I instead just do a requestPermission in componentDidMount. Do this before registering any listeners.
  2. I put a listener on onTokenRefresh to upload new token to the server, but I suspect it doesn’t always get called when the token changes. This causes my backend to sometimes send message to invalid token. I’m not sure of the repro case here. To workaround this you might want to upload current token when app becomes active or in componentDidMount.
  3. Apple has some restrictions on Push Notifications and Silent Pushes. (Silent Push is the same as what RNFirebase calls “data-only” message). Background silent pushes are throttled, if you send more than 2-3 per hour you may not receive all of them. This may be why onMessage() is only triggered sometimes when your app is backgrounded.
  4. Testing conditions. If you’re using Xcode debugger attached to your app, the debugger will disable the aforementioned throttling and then all silent pushes will suddenly work. This confused me for a while, I thought I was dealing with a heisenbug.

Resources
https://developer.apple.com/library/archive/technotes/tn2265/_index.html
https://forums.developer.apple.com/thread/89877

This is all assuming you’ve installed everything correctly and are sending messages from your backend correctly (i.e. content-available=true, etc).

After understanding the above, the behaviors are now a little more predictable. I tested my app using RNFirebase 4.3.x and 5.5.x; the behaviors are the same. Foreground notifications/messages trigger onNotification()/onMessage() respectively. Background notifications/messages don’t trigger anything except onNotificationOpened (I assume I’m running into throttling since attaching Xcode debugger makes background messages trigger onMessage()). I still have occasional (but rare) problems with messaging and notifications completely not working on install; force kill usually makes it work.

Hope this helps somebody out there.

Edit: If you want to see if your silent pushes are being throttled by iOS, you can go into Xcode -> Window -> Devices and Simulators -> Select your device -> Open Console, then search the logs for something like "push" or your app bundle id. If your app is getting throttled by iOS, you'll see log entries like CANCELED: com.apple.pushLaunch.com.mycompany.myapp>:E50DWQ at priority 5 <private>!

@mikehardy
Copy link
Collaborator

@TimMun that's a fantastic explanation of a lot of the intricacies - it matches with my experience as well. And it's also why I almost refuse to help on notifications and messaging questions anymore - the info is all out there and it's possible to slowly, carefully, verify all these things but it is slow and you have to be careful! Slow is fast in this area. Would be very interested to see your future learnings on token refresh - what I've seen from the auto-test-suite attached to react-native-firebase is that the token refresh is potentially very asynchronous. It takes 10-20s on my (slow, far from google) connection, perhaps that has an interaction somewhere and results in dropped refreshes or some sort of race?

@thecodecafe
Copy link

thecodecafe commented Oct 3, 2019

For those who are still facing this, please make sure that you have push notification service key created in your developer account of apple, and upload this key with key id and team id to your firebase app in firebase console. For complete setup follow this video -> https://www.youtube.com/watch?v=zeW8DO5KZ8Q

@sam17896 Thanks, my issue was that I had not added the APN key to the cloud message config for my app, found that out form the video, thanks mate!

mikehardy pushed a commit to invertase/react-native-firebase-docs that referenced this issue Oct 19, 2019
For the current latest version (5.x) of RN Firebase, calling `requestPermission` also calls the `registerForRemoteNotifications` method. This is required for the fcm token retrieved to be associated to a valid APNS token, and for push notifications to be delivered correctly to the device. (invertase/react-native-firebase#1203 (comment))

I have been debugging an issue with push notifications and consistently calling the `requestPermission` method even when the user already granted permissions was the only fix.
There is also a `firebase.messaging().ios.registerForRemoteNotifications()` method available, but I found that when I called it from the JS thread, a warning popped up in Xcode saying that this method (the underlying `[RCTSharedApplication() registerForRemoteNotifications]` call) should only be made from the main thread.

This does not prompt the user on iOS after the first time the user responds to the dialog, so the user experience is not hurt by running this code over and over.
@camel113
Copy link

camel113 commented Oct 20, 2019

I am wondering where you found this line [UNUserNotificationCenter currentNotificationCenter].delegate = self; (in AppDelegate.m)on the docs. This is what I was missing and solved my problem.

@iocuydi
Copy link

iocuydi commented Jan 10, 2020

For anyone still struggling with this, I followed everything here and it still didn't work. What finally made it work was adding

[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];

as the very last line before "return YES;" in didFinishLaunchingWithOptions.

Note that I also had the block of extra code above (if ([UNUserNotificationCenter class] != nil) {....), but it did not work without adding that last line at the end of the method.

@deepas96
Copy link

@chriswang101 Your solution worked for me like magic! Thanks alot

@danielroccha
Copy link

I spent a few hour after i discover that it is necessary call firebase.messaging().ios.registerForRemoteNotifications() for receive remote notifications

@Dror-Bar
Copy link

Dror-Bar commented Feb 4, 2020

Lots of good suggestions here, unfortunately none of them worked for me.
IOS just didn't receive any notifications from Firebase. Radio silent.

At the end, what worked for me was never mentioned here: Waiting.
After following the documentation and installing on IOS device, I just waited about an hour or so and suddenly, notification sent from Firebase Console was received immediately.

@mkmule
Copy link

mkmule commented Feb 4, 2020

I did spend some time on this issue as well ("react-native-firebase": "^5.6.0"), in my case a problem was a missing APNs Authentication Key. Make sure you did create it from Apple Developer Program and upload to Firebase Cloud messaging configuration.

Here is a guide which explains required steps: https://medium.com/forddev/react-native-firebase-how-to-send-push-notifications-on-ios-android-part-1-b322d715b79d

Regarding AppDelegate.m:

#import <Firebase.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"

and

  [FIRApp configure];
  [RNFirebaseNotifications configure];
  [application registerForRemoteNotifications];

was enough to make things work using:

    firebase.notifications().onNotification(notification => {
      if (Platform.OS === 'android') {
        notification.android.setChannelId('insider').setSound('default');
      }

      firebase.notifications().displayNotification(notification);
    });

@fukuball
Copy link

@sdqwerty It works!

@teodorciuraru
Copy link

@yarian thank you so much - For everyone not receiving pushes - request Permission is required even if you have pushes already enabled!! I am migrating a swift app to react native and wasn't receiving pushes even though I had the token. Just calling requestPermission fixed it.

Even in V6 this solves the bug.

@maihonganh1997
Copy link

Thank @sanjcho
it work for me!

@dgana
Copy link

dgana commented Apr 2, 2020

I got the notifications working remotely in iOS 13.4. but my problem right now it's just the delayed notifications sometimes for about 15 minutes. But after i received it the next notification will be fast about 1 - 2 seconds.

Anyone experiencing this issue?

My index.js code using firebase cloud function

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': '...',
        },
        payload: {
          aps: {
            alert: {
              title,
              body,
            },
            sound,
            contentAvailable: true,
          },
        },
      },
      tokens: [...],
    };
    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"

@Dror-Bar
Copy link

Dror-Bar commented Apr 2, 2020

@dgana If you are getting the notifications, but only experiencing some delay, it sounds to me like the issue is not related to this library.

It's possible that if you are sending too many notifications and not opening them on the device firebase might "penalize" you and start delaying notifications (or even not sending at all) but I'm not sure.

@jobran41
Copy link

jobran41 commented Jun 6, 2020

#import <UserNotifications/UserNotifications.h>

thx @chriswang101

@Stas-Buzunko
Copy link
Contributor

#1203 (comment) worked for me

@pdkcoder
Copy link

Hi everyone!
Encountered a similar problem and all of this suggestions don't work for me. Solved by setting FirebaseAppDelegateProxyEnabled to yes in info.plist and reinstalling app on test iPhone. Hope it helps somebody.

This works for me too.

@AlexisTonneau
Copy link

Hi everyone!
Encountered a similar problem and all of this suggestions don't work for me. Solved by setting FirebaseAppDelegateProxyEnabled to yes in info.plist and reinstalling app on test iPhone. Hope it helps somebody.

Fixed the issue even with @react-native-firebase/messaging 10.5.1 ! I suggest you to check out this solution if you have multiple connection errors in your Xcode console 📶

@xiuwangthoughtworks
Copy link

I got the notifications working remotely in iOS 13.4. but my problem right now it's just the delayed notifications sometimes for about 15 minutes. But after i received it the next notification will be fast about 1 - 2 seconds.

Anyone experiencing this issue?

My index.js code using firebase cloud function

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': '...',
        },
        payload: {
          aps: {
            alert: {
              title,
              body,
            },
            sound,
            contentAvailable: true,
          },
        },
      },
      tokens: [...],
    };
    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"

I have the same issue, how do you solved this problem?

@mikehardy
Copy link
Collaborator

@xiuwangthoughtworks I think this is somewhat normal. Just because we as developers want things to happen does not mean we own the user's battery. The user does and the operating system does it's best to only actually run things periodically in batches. Sounds like what is happening here.

@xiuwangthoughtworks
Copy link

@xiuwangthoughtworks I think this is somewhat normal. Just because we as developers want things to happen does not mean we own the user's battery. The user does and the operating system does it's best to only actually run things periodically in batches. Sounds like what is happening here.

See my other detailed description

@mym0404
Copy link

mym0404 commented Feb 12, 2022

I spent a few days digging into this. I think the reason there are so many varying reports as to what works and what doesn’t is due in part to a few factors: 1.) not calling requestPermission; 2.) FCM token is not updated correctly; 3.) iOS and APNS throttling; and 4.) testing conditions. (All this is relevant to iOS only)

  1. As pointed out elsewhere and in various other threads regarding why messages/notifications don’t work: you need to call firebase.messaging().requestPermission(), even if hasPermission() says they’re already granted. chriswang’s solution above (putting that block of code in AppDelegate.m) basically does the same thing as requestPermission (in fact, see RNFirebaseMessaging.m, method requestPermission() ); it works because it’s executing similar code as requestPermission every time your app starts up. For me, I instead just do a requestPermission in componentDidMount. Do this before registering any listeners.
  2. I put a listener on onTokenRefresh to upload new token to the server, but I suspect it doesn’t always get called when the token changes. This causes my backend to sometimes send message to invalid token. I’m not sure of the repro case here. To workaround this you might want to upload current token when app becomes active or in componentDidMount.
  3. Apple has some restrictions on Push Notifications and Silent Pushes. (Silent Push is the same as what RNFirebase calls “data-only” message). Background silent pushes are throttled, if you send more than 2-3 per hour you may not receive all of them. This may be why onMessage() is only triggered sometimes when your app is backgrounded.
  4. Testing conditions. If you’re using Xcode debugger attached to your app, the debugger will disable the aforementioned throttling and then all silent pushes will suddenly work. This confused me for a while, I thought I was dealing with a heisenbug.

Resources https://developer.apple.com/library/archive/technotes/tn2265/_index.html https://forums.developer.apple.com/thread/89877

This is all assuming you’ve installed everything correctly and are sending messages from your backend correctly (i.e. content-available=true, etc).

After understanding the above, the behaviors are now a little more predictable. I tested my app using RNFirebase 4.3.x and 5.5.x; the behaviors are the same. Foreground notifications/messages trigger onNotification()/onMessage() respectively. Background notifications/messages don’t trigger anything except onNotificationOpened (I assume I’m running into throttling since attaching Xcode debugger makes background messages trigger onMessage()). I still have occasional (but rare) problems with messaging and notifications completely not working on install; force kill usually makes it work.

Hope this helps somebody out there.

Edit: If you want to see if your silent pushes are being throttled by iOS, you can go into Xcode -> Window -> Devices and Simulators -> Select your device -> Open Console, then search the logs for something like "push" or your app bundle id. If your app is getting throttled by iOS, you'll see log entries like CANCELED: com.apple.pushLaunch.com.mycompany.myapp>:E50DWQ at priority 5 <private>!

@TimMun How can I resolve throttled silent notification in my device?
I debugged two days and finally find this is a issue....
image

I can resolved this issue with Settings-screen sharing - notification on
Is there any other solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests