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

SetBackgroundHandler not working on ios. #3530

Closed
2 of 10 tasks
tranty9597 opened this issue Apr 24, 2020 · 85 comments
Closed
2 of 10 tasks

SetBackgroundHandler not working on ios. #3530

tranty9597 opened this issue Apr 24, 2020 · 85 comments
Labels
platform: ios plugin: messaging FCM only - ( messaging() ) - do not use for Notifications

Comments

@tranty9597
Copy link

tranty9597 commented Apr 24, 2020

SetBackgroundHandler not working on ios.

I've setup rnfirebase/message v6 for my project, and up to now it's work perfectlty on android. But on IOS SetBackgroundHandler dot not trigger any event.

I've try to debug on xcode at RNFBMessaging+AppDelegate.m and RNFBMessaging+UNUserNotificationCenter.m, and when app in background, didReceiveRemoteNotification delegate dont be fired while my notification still be presented.

Do I have to add content-available to my message payload to make it works?


Project Files

Javascript

Click To Expand

package.json:

# N/A

firebase.json for react-native-firebase v6:

# N/A

iOS

Click To Expand

ios/Podfile:

  • I'm not using Pods
  • I'm using Pods and my Podfile looks like:
# N/A

AppDelegate.m:

// N/A


Android

Click To Expand

Have you converted to AndroidX?

  • my application is an AndroidX application?
  • I am using android/gradle.settings jetifier=true for Android compatibility?
  • I am using the NPM package jetifier for react-native compatibility?

android/build.gradle:

// N/A

android/app/build.gradle:

// N/A

android/settings.gradle:

// N/A

MainApplication.java:

// N/A

AndroidManifest.xml:

<!-- N/A -->


Environment

Click To Expand

react-native info output:

 OUTPUT GOES HERE
  • Platform that you're experiencing the issue on:
    • iOS
    • Android
    • iOS but have not tested behavior on Android
    • Android but have not tested behavior on iOS
    • Both
  • react-native-firebase version you're using that has this issue:
    • 6.7.1
  • Firebase module(s) you're using that has the issue:
    • FirebaseMessaging
  • Are you using TypeScript?
    • Y


@Ehesp
Copy link
Member

Ehesp commented Apr 24, 2020

Can you post some code too? Have you followed https://rnfirebase.io/messaging/usage/ios-setup ?

@tranty9597
Copy link
Author

tranty9597 commented Apr 24, 2020

Can you post some code too? Have you followed https://rnfirebase.io/messaging/usage/ios-setup ?
Yes, I do follow this. And I've already get notification present but the delegete is not getting called.
This is my index.js
Screen Shot 2020-04-24 at 15 45 28
And this works well on android.
Screen Shot 2020-04-24 at 15 46 33

@Ehesp
Copy link
Member

Ehesp commented Apr 24, 2020

Can you post your App delegate file for iOS

@tranty9597
Copy link
Author

Can you post your App delegate file for iOS
Yep, It has nothing. just [Firbase confiure] and default react native configuration

Screen Shot 2020-04-24 at 20 13 31

@Ehesp
Copy link
Member

Ehesp commented Apr 24, 2020

Code please so we can copy bits

@tranty9597
Copy link
Author

tranty9597 commented Apr 24, 2020

Yep, sorry about that

/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
// splashScreen 
#import "RNSplashScreen.h"
#import <Firebase.h>
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"dulich"
                                            initialProperties:nil];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

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

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

@giftset
Copy link

giftset commented Apr 26, 2020

Me, too. Even When the device get the silent push(data only),setBackgroundMessageHandler is not triggered on ios at the version of both of v6.4.0 and v6.7.1

@Ehesp
Copy link
Member

Ehesp commented Apr 26, 2020

What data payloads are you sending over?

@giftset
Copy link

giftset commented Apr 26, 2020

I figured it out.

from doc, it says content_available property is placed in apns, but when we put it out of apns, it started to work

data: {
to: notificationKey,
content_available: true, <-- this is the key to wake up application
priority: "high",
data: payload.data
}

@Ehesp
Copy link
Member

Ehesp commented Apr 26, 2020

Oh interesting, what sdk are you using?

@robertqin86
Copy link

robertqin86 commented Apr 26, 2020

Hey guys, this is unfortunately a serious problem. I have followed everything judiciously but the background handler is just not working on iOS in 6.7.1 for "@react-native-firebase/messaging": "^6.7.1",. I am using notifee and so far, everything woks flawlessly for Android but not on iOS.

I have configured push notifications correctly and was previously on v5 and the notifications worked as expected. With this v6 upgrade, I am using FBRN messaging to receive data messages and notifee to trigger local notifications. Notifee is working as expected but the background handler is not being triggered at all for iOS, so there's nothing I can do with notifee.

I'm using iPhone 8 plus on 13.3.1

GCF Function:

await messaging.sendToDevice(
      [iosToken],
    {
      data: {
        title: 'Title',
        body: 'Body'
      },
    },
    {
      // Required for background/quit data-only messages on iOS
      contentAvailable: true,
      // Required for background/quit data-only messages on Android
      priority: 'high',
    }
  );

// index.js background listener

messaging.setBackgroundMessageHandler(async (remoteMessage) => {
 // this is NEVER CALLED on iOS 
  console.log("Message handled in the background!", remoteMessage);
  await displayNotification(remoteMessage.data);
});

function HeadlessCheck({ isHeadless }) {
  if (isHeadless) {
    // App has been launched in the background by iOS, ignore
    return null;
  }

  return <App />;
}

// Current main application
AppRegistry.registerComponent(appName, () => HeadlessCheck);

App.js

async componentDidMount() {
    try {
      await messaging.registerDeviceForRemoteMessages();

      notifee?.onForegroundEvent(({ type, detail }) => {
        switch (type) {
          case EventType.DISMISSED:
            console.log("User dismissed notification", detail.notification);
            break;
          case EventType.PRESS:
            console.log("User pressed notification", detail.notification);
            break;
        }
      });

      notifee?.onBackgroundEvent(async ({ type, detail }) => {
        const { notification, pressAction } = detail;
        // Check if the user pressed the "Mark as read" action
        if (type === EventType.ACTION_PRESS && pressAction.id === "default") {
          // Remove the notification
          await notifee.cancelNotification(notification.id);
        }
      });

      const authorizationStatus = await messaging.requestPermission();
      if (
        authorizationStatus ===
          messagingStatics.AuthorizationStatus.AUTHORIZED ||
        authorizationStatus === messagingStatics.AuthorizationStatus.PROVISIONAL
      ) {
        const fcmToken = await messaging.getToken();
        store.dispatch(setFCMToken(fcmToken));
        // This is called on both iOS and Android in foreground
        this.unsubscribe = messaging.onMessage(async (remoteMessage) => {
          console.log("FCM Message Data:", remoteMessage);
          await displayNotification(remoteMessage.data);
        });
      }
    } catch (err) {
      // handle request errors
      console.log("token related errors", err);
    }
  }

@Ehesp
Copy link
Member

Ehesp commented Apr 26, 2020

Can check native logs for any messages? And when you say background do you mean no events for any type of message?

@robertqin86
Copy link

robertqin86 commented Apr 27, 2020

Hey @Ehesp ! Thanks for your reply! I was following #3367 too and used the console app to find any logs from my iphone device but I did not find any push notification specific logs.

To clarify, when I say background, what I meant was, on iOS, the firebase messaging setBackgroundMessageHandler callback is never called after sending FCM message when the app is in the background. Only when I launch the app in the foreground, the onMessage containing the fcm message is triggered.

On Android, everything works as expected for both callbacks. I have also added priority high and content available true to my payload.

await messaging.sendToDevice(
      [iosToken],
    {
      data: {
        title: 'Title',
        body: 'Body'
      },
    },
    {
      // Required for background/quit data-only messages on iOS
      contentAvailable: true,
      // Required for background/quit data-only messages on Android
      priority: 'high',
    }
  );

This also does not work

const messageIOS = {
    data: {
      title: 'Title',
      body:
        'body',
    },
    android: {
      priority: 'high',
    },
    apns: {
      headers: {
        // 'apns-priority': '5',
        'apns-push-type': 'background',
        'apns-topic': '<my bundle id>'
      },
      payload: {
        aps: {
          'content-available': 1,
          // contentAvailable: true
        },
      },
    },
    token: iosToken,
  };

using messaging().send(messageIOS);

@tranty9597
Copy link
Author

I figured it out.

from doc, it says content_available property is placed in apns, but when we put it out of apns, it started to work

data: {
to: notificationKey,
content_available: true, <-- this is the key to wake up application
priority: "high",
data: payload.data
}

Yep, as I mentioned on this issue's description, I have to put content_available into message payload to make it work on background and teminated state, and maybe It's a mandatory and importance field that not be in the document.

We use UNUserNotificationCenter for listen event when notification change but I dont see any delegate listen to background event from this framework. (willPresentNotification: foreground notification, willReceiveNotificationResponse: for notification interaction)

RNFirebaseMessage fires background_message_received in AppDelegate.didReceiveRemoteNotification only, and this delegate is not be fired while notificaion has comming and presenting.

@robertqin86
Copy link

Update: I tried the payload recommended by others in this thread. Instead of using the firebase node library, I did a call to FCM (https://fcm.googleapis.com/fcm/send) using postman.

// Headers omitted for brevity...

{ "data": {
    "title": "5x1",
    "body": "15:10"
  },
  "content_available": true,
  "priority": "high",
  "to" : "<device token>"
}

Same scenario observed. Messages are only received when the app is in the foreground and not in the background handler.

@VictorKolb
Copy link

It is very strange. Half hour ago notifications is not received notification when app is quit or background. Foreground messaging is always received. Now on IOS all worked well even though I haven't changed the code.

But on android don't work when app is quit :(

"@react-native-firebase/messaging": "^6.7.1" – package version.

@Ehesp
Copy link
Member

Ehesp commented Apr 27, 2020

iOS block messages quite heavily if you've been spamming them - that could be a reason. Unfortunately things are just overall a problem for devs, if you google iOS messaging issues it's a minefield :(

@VictorKolb
Copy link

VictorKolb commented Apr 27, 2020

@Ehesp No, I didn't send spam. Only debug messages every 10 minutes to one token... but there is no other explanation.

@mikehardy
Copy link
Collaborator

One person's definition of spam doesn't fit anothers. I believe that's too much for iOS even

@Ehesp
Copy link
Member

Ehesp commented Apr 27, 2020

@Ehesp No, I didn't send spam. Only debug messages every 10 minutes to one token... but there is no other explanation.

Sending a content-available message at a rate of once per 10 minutes could well be deemed as spam, since you'd be waking the app up every 10 minutes.

I'm not sure what else to say really - it's a very frustrating issue which is hard to replicate.

@VictorKolb
Copy link

But in this moment on android not working only when app is quit. When app foreground or background is worked. Oh guys, complicated situation 😆

@Ehesp
Copy link
Member

Ehesp commented Apr 27, 2020

Android should be much easier to debug and see what's going on. If you open Logcat and send a message, you should get some messages with what is happening behind the scenes.

@dcloux
Copy link

dcloux commented Apr 30, 2020

We have the same problem (all the tests are done with physical devices).
On Android, it works without any problem.
On iOS, it worked for about 15 minutes, then nothing on a device. While on a second device it continued to work. The result also depends if the application is closed or in the background or if the iPhone is locked or not.
It's as if it doesn't depend on the code itself, but rather of iOS itself.

@mikehardy
Copy link
Collaborator

@dcloux
For a fun read, go down the internet rabbit hole of searching for something like "inconsistent ios push message delivery" and read everything you can :-). APNS and iOS both are unreliable and lossy, and documented as such according to my read. APNS might throttle you for whatever metrics they decide on, but are documented vaguely as "sending too many messages", and iOS might throttle you for things vaguely documented as "consuming too much energy" and their AI gives you an energy budget based on app interaction etc.

As a developer that wants consistent behavior to understand implementation correctness, it's terrible

@robertqin86
Copy link

robertqin86 commented Apr 30, 2020

Hi @mikehardy I understand APNS might be unreliable, but I was still receiving pushing notifications on my iOS device previously on v5 of the RNFB messaging library. Since the upgrade to v6, I have not been receiving a single silent notification in the setBackgroundHandler on my iPhone device. I think it comes down to the following scenarios:

  1. Firebase Configuration issues (unlikely since I received the notifications on v5 of the RNFB library and I'm also receiving the message when the app is in the foreground in the onMessage handler of v6)
  2. My backend data payload issue. It's possible, but I can't see where I've gone wrong below. I've tried every possible key combinations, including those that are commented out.
const messageIOS = {
    data: {
      title: 'Title',
      body:
        'body',
    },
    android: {
      priority: 'high',
    },
    apns: {
      headers: {
        // 'apns-priority': '5',
        'apns-push-type': 'background',
        // 'apns-topic': '<my bundle id>'
      },
      payload: {
        aps: {
          'content-available': 1,
          // contentAvailable: true
        },
      },
    },
    token: iosToken,
  };
messaging().send(messageIOS);
  1. setBackgroundHandler doesn't work properly for iOS on v6. This was previously available on Android only, and was only recently made available for iOS devices with 6.4.0-rc2: See feat(messaging): ios & android messaging updates & fixes #3339. My gut feeling is the setBackgroundHandler isn't implemented properly on the native layer on iOS. I've tried debugging FIRMessagingRemoteNotificationsProxy.m and other relevant files but for some reason, didReceiveRemoteNotification was never called.
#pragma mark - GULApplicationDelegate
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (void)application:(GULApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
}

I'll continue to debug 2 and 3. I don't think its a simple trottle issue on Apple's side. It's probably something relating to silent push notifications restrictions on iOS 13 devices. Because I'm using notifee, based on the documentation, I have to schedule a silent data notification to activate setBackgroundHandler when the device is in the quit or inactive state, then use notifee to trigger a local notification. Its working beautifully on Android, but not on iOS, purely because setBackgroundHandler is never triggered for my iOS device running 13.3.1.

@mikehardy
Copy link
Collaborator

Okay @dcloux when you say "same problem" then, it's important to note that you aren't the original poster, so we can't verify your assertion of sameness. Can you verify you are running the latest versions (RNFB 6.7.1 I think?) so you definitely have the benefit of #3339 ?

@kunalword
Copy link

In iOS How to catch a push notification in background without user interaction? android working fine getting response at setBackgroundMessageHandler.

@mikehardy
Copy link
Collaborator

@kunalword using exactly the information in the comment I posted above yours, in combination with the documents for the background message handler in the messaging section of rnfirebase.io

@hasansultan92
Copy link

So essentially we need to set the 'apns' property as part of the payload to trigger the functionality when the app is closed?

I have tried that from my backend and the result is the same ( app doesn't trigger the setBackgroundMessageHandler() functionality in the background)

@mikehardy
Copy link
Collaborator

@hasansultan92 Launch on a real device and watch console. Yes, send content-available in apns or it will not work with data only messages. If the user has swiped your app away your app is dead until a new user interaction, that's operating system policy. If you have been spending the power of the device too heavily iOS will throttle you. If your code and config isn't correct nothing will work. It is not easy but it does work when done correctly.

@hasansultan92
Copy link

Hey so yes I have been using a real device and I used Xcode to build the app on the device. I can see the logs when the app is in background state(minimized) but obviously once I close the app on the device, the logs and connection to Xcode gets terminated so I can't really see what's happening when a message is being sent while the app is closed. The library/modules are working just fine on android.

I am sending notification plus data using my backend with the Admin SDK and whichever device I send it to, the notification pops up right away (including iOS even when in quit state) but just the background processes aren't being triggered for iOS. I did check my app power usage and it was high on a iPhone 6 however(that's probably because of the enormous number of console logs I was working with earlier). Please note I tried to check if the functionality was working in production env by uploading the app to TestFlight but yea that didn't work either. Im doubting my appdelegate.m config since I don't understand objective C so maybe if you have the simplest form of appdelegate.m that works could you share that? I also noticed iOS enabled some keys in info.plist and Id like to confirm if that's normal cause I have not seen any information about them so far.

@mikehardy
Copy link
Collaborator

Use Console.app
If you send notification in the payload, not data only, your messages receive different handling
AppDelegate shouldn't need anything i RNFBv6, just follow the rnfirebase.io docs

@hasansultan92
Copy link

hasansultan92 commented Sep 19, 2020

@mikehardy not sure what you mean by Console.app, is it the remote debugger using chrome?

As far as the docs show on firebase.io the handlers handling the messages with notification+ data are onMessage() - this works for sure - and setBackgroundMessageHandler()- doesn't work when app is quit in iOS.

Also Im not using RNFBv6, my packages are "@react-native-firebase/app": "^8.4.2", "@react-native-firebase/messaging": "^7.8.6", in package.json and I believe the corresponding numbers in the pod file.

If your sure this issue isn't a problem anymore on v6 I don't mind setting up the older version to be honest.

@mikehardy
Copy link
Collaborator

Definitely not the remote debugger with chrome. I believe that might even confound some of the functionality, I do not develop the debugger turned on, myself, as it executes the bundle off device and can have incorrectness side effects that are not expected.

Console.app is literally Console.app on your mac machine, while the real ios device is plugged in you may follow the devices logs.

Sorry the use of the phrase "v6" is imprecise and I should not have used it. There was a big break between V5 and V6 and we used to use "V6" as shorthand for "most current / modern". All of the versions are higher now of course, current stable is what I really intend.

setBackgroundMessageHandler does work when app is quit but not force closed / swiped away if that makes sense - the wording needs to be accurate/precise here. quit is the state when the app has been stopped by the OS in the background to preserve resources but the user did not actually kill the thing. In those cases, data only will work.

@hasansultan92
Copy link

hasansultan92 commented Sep 20, 2020

@mikehardy yea so I checked console.app from Xcode etc and yea indeed the device isn't registering the notification that came when the app has been killed/swiped off from the app drawer. I can see a log for the speaker to make a sound when the message comes in but nothing else no errors either. I however, can see the logs for a notification when the app is in background(minimized) and in foreground. To eliminate the CPU throttling fact that has been mentioned in several docs, I do not see any logs for cpu usage being high or anything when the app is in background or foreground but I do see an instruction when the device is sitting idle doing nothing to reduce cpu power.

As for the following - 'setBackgroundMessageHandler does work when app is quit but not force closed / swiped away if that makes sense - the wording needs to be accurate/precise here.' - I am guessing when the message comes in and the app was swiped away it takes the app to a background only mode? This however is not working for me on iOS. I have been debugging this app for the past 1 week just so I can save the message being sent from another user but I guess Ill have to now try another push notification service as this headache Is beyond my knowledge. PS, I did try data only and no that did not work either.

If there is anyone who actually got this library to work please please dm me

@mikehardy
Copy link
Collaborator

@hasansultan92 - "app swiped" == your app is dead. You will never get logical control back until a user taps on a visible notification or launches your app.

@hasansultan92
Copy link

@mikehardy so essentially are u saying this is an iOS problem or something the library is not able to achieve? clearly when the app is swiped in android I can still perform the tasks I want using set backgroundHandler so Im gonna goes iOS on this. Ill tell you what I am trying to achieve and maybe you can tell me back if its impossible with this library or even push notifications in general. I am basically making a chat app and every time the receiving user is offline I want the push notifications to carry the data to the device and perform the actions to update local storage. Essentially if the user doesn't have my app running in the background or foreground on iOS he will never be able to see the new messages in the chat area. I obviously don't want to load all the messages from the db- it'll keep my server load busy and consumption of bandwidth will be high- so what other way can I solve this task of saving texts that were sent to the user when they were offline?

Yes, I am aware your a contributor to the library but you know, you might know the answer I am looking for

@mikehardy
Copy link
Collaborator

If the app is swiped the app is dead via ios policy. Iron law with the only exception being a notification may be posted to the notification center. You will need to do your own research and testing, my answers are brief but complete

@mikehardy
Copy link
Collaborator

...at least to the extent that I am not going to design your app architecture. That's on you of course, no offense

@hasansultan92
Copy link

@mikehardy none taken. Its just the docs stated that the app is allowed to run headless/in the background and the handler is going to be the same as the background state for the quit state. If I knew that this functionality is limited by either the library itself or how react-native works I wouldn't have spent nearly a week into this you know. its alright thank you for your feedback. back to the drawing board it is for me

@mikehardy
Copy link
Collaborator

headless is a complicated topic
In general it is android-specific / android only, it is a separate execution mode that bears examination on it's own, there are documents on react-native dev site about it

However, there is the case where your app on ios is fully launched (there is no true headless mode in ios), and there is a way to inject a property into the launch sequence simply so you can see if that is how you were launched in ios. This can happen if your app is allowed to start in response to a data-only cloud message, but is different than the "pure headless" mode that android has

You are implementing a pretty complicated system, in the exact areas that the operating systems protect the most (app starts, remote programming that requires permissions, energy usage etc). There's no avoiding the difficulty unfortunately. Make tiny example prototypes and test them is my advice. When I was developing this area of my app I just had a separate dev-only screen with buttons for each thing I wanted, and lots of logging and tested away until I found a mix of things that worked.

@hasansultan92
Copy link

I believe the how is UIApplicationLaunchOptionsRemoteNotificationKey and I don't know Objective-C/Swift so yea right now Im looking for some objective c developers who can help me. Since this is more of a react-native headache I am going to assume that apps like Airbnb, FB, etc use the native part to handle the notification data and save it etc because so far I don't see any other way that user messages can come to devices and be saved. Thank you for your help though @mikehardy .

@mikehardy
Copy link
Collaborator

I believe they fetch state from server on app startup when user interacts with notification. Have you ever gotten a new message notification from facebook but then interacted with it while in airplane mode? That will show more how other apps do this

@forbesgillikin
Copy link
Contributor

Ok. So. I have seen a lot of these threads over the last 2 months since I implemented Notifications in my app. The issue here is the RN Firebase Docs and the terminology used for different app states, coupled with a fundamental misunderstanding of how notifications work on iOS, and developers not doing their own docs research on the Apple Developer resources.

RN FIREBASE WORKS AS EXPECTED. YOU MUST UNDERSTAND THAT IF YOUR APP HAS BEEN CLOSED OR KILLED, BACKGROUND NOTIFICATIONS WILL NOT BE DELIVERED. THERE ARE NO PROBLEMS WITH THE RN FIREBASE CODE.

READ THE DOCUMENTATION FROM APPLE

https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app

Pushing Background Updates to Your App

Deliver notifications that wake your app and update it in the background.

IMPORTANT: Notifications that WAKE your app. If your app is closed, nothing will happen.

Background notifications are not useful in most common app frameworks. Stick to alert style notifications.

@justcodejs
Copy link

I had made a Firebase Push notification tutorial video hope it will help those who faced problem.

https://www.youtube.com/watch?v=wC3N-hxkWbk

@ch3tan03
Copy link

ch3tan03 commented Jan 2, 2021

Guys use below payload while sending data only notifications(remove title and body from notification) or data plus notifications

{
"registration_ids": [""],
"message" : "You Got A Call",
"priority": "high",
"notification": { "title": "msg for topic", "body": "bodytext", "content_available": "true" },
"data": {
"priority": "high",
"callType": "audio",
}
}

Index.js should be
messaging().setBackgroundMessageHandler(async remoteMessage => {
// your logic or put alert
});
function HeadlessCheck({ isHeadless }) {
if (isHeadless) {
// App has been launched in the background by iOS, ignore
return null;
}
return ;
}

// Current main application
AppRegistry.registerComponent(appName, () => HeadlessCheck);

setBackgroundMessageHandler works on both iOS and Android when app is minimized:)

@kitfai
Copy link

kitfai commented Jan 17, 2021

Guys use below payload while sending data only notifications(remove title and body from notification) or data plus notifications

{
"registration_ids": [""],
"message" : "You Got A Call",
"priority": "high",
"notification": { "title": "msg for topic", "body": "bodytext", "content_available": "true" },
"data": {
"priority": "high",
"callType": "audio",
}
}

Index.js should be
messaging().setBackgroundMessageHandler(async remoteMessage => {
// your logic or put alert
});
function HeadlessCheck({ isHeadless }) {
if (isHeadless) {
// App has been launched in the background by iOS, ignore
return null;
}
return ;
}

// Current main application
AppRegistry.registerComponent(appName, () => HeadlessCheck);

setBackgroundMessageHandler works on both iOS and Android when app is minimized:)

Hi @ch3tan03 .

I saw you mentioned tha "sending data only notifications(remove title and body from notification) or data plus notifications",but in your notification tag , there are title and body? Can you elaborate more?

Thanks

@yasir-netlinks
Copy link

yasir-netlinks commented Jan 31, 2021

I am facing a similar problem using the latest version 10.5.1. The setBackgroundMessageHandler doesn't trigger when the app is in quit state. However, the app wakes up on OS versions <= 14.3. But on the latest versions of OS it doesn't wake the device.
Any ideas guys, this is really frustrating.

@yasir-netlinks
Copy link

It seems that I have got it to work. I had content_available and priority appropriately set and yet the setBackMessageHandler didn't trigger when the app is in quit state, and I'm sending data-only -- silent notification.
it seems that setting this did the job: https://rnfirebase.io/messaging/usage#background-application-state.
Don't forget to inject isHeadless in your AppDelegate.m too.

I am using legacy API and this is the payload, hope this might help

{
  "to": "/topics/myTopic",
  "priority": "high",
  "content_available": true,
  "data": {}
 }

@harutyundr
Copy link

Hi everyone,

I had the same issue and I managed to resolve it by including it "content-available" => 1, in the message. I see several people mention content_available, contentAvailable and other keys, and it is also not clear where exactly the key should be specified. So the structure that worked for me was (using PHP, but I guess it represent the structure required by the REST API itself):

[
    // use data in the application to build custom local notifications
    'data' => [
        'custom_title' => 'LOCAL - $GOOG up 1.43% on the day',
        'custom_body' => '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ],
    'apns' => [
        'headers' => [
            'apns-priority' => '10',
        ],
        'payload' => [
            'aps' => [
                "content-available" => 1,
                'badge' => random_int(1, 100),
            ],
        ],
    ]
]

I provide a random badge count with each request as it seems iOS always updates this count, even if the content never reaches the app and my callback is not invoked, so this was an easy way to understand if my message is properly formatted.

@barghi
Copy link

barghi commented Aug 3, 2021

Hi everyone,

This works for me in both Android and iOS
and of course, you can use these methods in Hooks.

https://rnfirebase.io/messaging/notifications#main

componentDidMount() {
    this._handleNotification();
}

_handleNotification() {
      // 'Notification caused app to open from background state:'
      messaging()
            .onNotificationOpenedApp(remoteMessage => {
                  console.log(remoteMessage);
            });

      // 'Notification caused app to open from quit state'
      messaging()
            .getInitialNotification()
                  .then(remoteMessage => {
                        console.log(remoteMessage);
                  });
}

@rnike
Copy link
Contributor

rnike commented Mar 3, 2022

Hi everyone,

I had the same issue and I managed to resolve it by including it "content-available" => 1, in the message. I see several people mention content_available, contentAvailable and other keys, and it is also not clear where exactly the key should be specified. So the structure that worked for me was (using PHP, but I guess it represent the structure required by the REST API itself):

[
    // use data in the application to build custom local notifications
    'data' => [
        'custom_title' => 'LOCAL - $GOOG up 1.43% on the day',
        'custom_body' => '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ],
    'apns' => [
        'headers' => [
            'apns-priority' => '10',
        ],
        'payload' => [
            'aps' => [
                "content-available" => 1,
                'badge' => random_int(1, 100),
            ],
        ],
    ]
]

I provide a random badge count with each request as it seems iOS always updates this count, even if the content never reaches the app and my callback is not invoked, so this was an easy way to understand if my message is properly formatted.

I believed the key depends on which API we're using, for Lagacy API we are using it with content_available, in your case you are using v1 API and the key will be content-available

@mikehardy
Copy link
Collaborator

Depends on the library you are using to generate the JSON as well, or if it's raw.
If you use firebase-admin-sdk, that's a library that will then generate JSON, and it uses contentAvailable.
The raw key that Apple's APNs servers actually consume in json is content-available though.
Perhaps if you use Python it's content_available

The documentation for your library will tell you. Or if you are doing raw JSON then the Apple docs tell you. You must use the appropriate key for your context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
platform: ios plugin: messaging FCM only - ( messaging() ) - do not use for Notifications
Projects
None yet
Development

No branches or pull requests