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

[🐛] Bug Report Title - setBackgroundMessageHandler is not working on IOS using react-native-firebase. #5057

Closed
jjkim0816 opened this issue Mar 22, 2021 · 14 comments
Labels
help: needs-triage Issue needs additional investigation/triaging. type: bug New bug report

Comments

@jjkim0816
Copy link

use library version

version

react-native-firebase v11.1.1

issue

App is turned off or hidden, setBackgroundMessageHandler is not working on IOS.
Now, just Fireabase will not use setBackgroundMessageHandler, so use onBackgroundMessage instead.
But, react-native-firebase don't use onBackgroundMessage, so what is the function instead of like onBackgroundMessage.

@jjkim0816 jjkim0816 added help: needs-triage Issue needs additional investigation/triaging. type: bug New bug report labels Mar 22, 2021
@SauloDesenvolvedor
Copy link

SauloDesenvolvedor commented Mar 22, 2021

@jjkim0816 , I am experiencing the same problem. In my case, onMessage is not activated. Is your onMessage fired on iOS?

On Android, everything is ok! onMessage() and setBackgroundMessageHandler().

@Wanderlust-sol
Copy link

@SauloDesenvolvedor Hi, I'm a colleague of @jjkim0816
yes, onMessage is fired on ios. but setBackgroundMessageHandler is not fired on quit state.
I found it was fired on background state while I sent 1-2 push-notification as soon as I made my app background state.

@jjkim0816
Copy link
Author

jjkim0816 commented Mar 22, 2021

@SauloDesenvolvedor Thank you so much, reply my question^^

@SauloDesenvolvedor
Copy link

In my case, onMessage is not enabled for iOS. How is your AppDelegate.m?

@jjkim0816
Copy link
Author

jjkim0816 commented Mar 22, 2021

@SauloDesenvolvedor So, we added "apns-push-type": "background" in Headers on APNS, and in testing.
We can't be sure this is answer, but we try to solve this problem.

@jjkim0816 jjkim0816 reopened this Mar 22, 2021
@SauloDesenvolvedor
Copy link

"apns-push-type": "background" work for you?

@SauloDesenvolvedor
Copy link

I am sending test notifications through the firebase panel.

Everything works on Android, onMessage and setBackgroundMessageHandler, including all other methods.

On iOS, none work.

Testing on real devices.

Could it be that the problem is in sending the notification through the firebase panel?

@Wanderlust-sol
Copy link

Wanderlust-sol commented Mar 22, 2021

#import "RNFBMessagingModule.h"
#import <Firebase.h>

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <KakaoOpenSDK/KakaoOpenSDK.h>

#import "RNBootSplash.h"

// push-notification 추가
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>

#ifdef FB_SONARKIT_ENABLED
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>

static void InitializeFlipper(UIApplication *application) {
  FlipperClient *client = [FlipperClient sharedClient];
  SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
  [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
  [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
  [client addPlugin:[FlipperKitReactPlugin new]];
  [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
  [client start];
}
#endif

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
    
  // clear data cached by firebase
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![defaults boolForKey:@"notFirstRun"]) {
      [defaults setBool:YES forKey:@"notFirstRun"];
      [defaults synchronize];
      [[FIRAuth auth] signOut:NULL];
    }
  }

#ifdef FB_SONARKIT_ENABLED
  InitializeFlipper(application);
#endif

  [[FBSDKApplicationDelegate sharedInstance] application:application
                           didFinishLaunchingWithOptions:launchOptions];
  [KOSession sharedSession].automaticPeriodicRefresh = YES;
  
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  
  // FCM isHeadless 관련 코드 start
  NSDictionary *appProperties = [RNFBMessagingModule addCustomPropsToUserProps:nil withLaunchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"malmoyFrontend"
                                            initialProperties:appProperties];

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

  [RNBootSplash initWithStoryboard:@"BootSplash" rootView:rootView]; // <- initialization using the storyboard file name
  
  // push notification 추가
 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
   center.delegate = self;
  
  return YES;
}



- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{ if ([[FBSDKApplicationDelegate sharedInstance] application:application openURL:url options:options]) {
    return YES;
  } else if ([KOSession isKakaoAccountLoginCallback:url]) {
    return [KOSession handleOpenURL:url];
  }

  return false;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
                                      sourceApplication:(NSString *)sourceApplication
                                              annotation:(id)annotation {
    if ([KOSession isKakaoAccountLoginCallback:url]) {
        return [KOSession handleOpenURL:url];
    }

    return false;
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [KOSession handleDidBecomeActive];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [KOSession handleDidEnterBackground];
}
 
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  NSLog(@"토큰: %@", deviceToken);

[RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  NSLog(@"제발: %@", userInfo);

 [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for localNotification event
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
        withCompletionHandler:(void (^)(void))completionHandler
{
 [RNCPushNotificationIOS didReceiveNotificationResponse:response];
}

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
 completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}


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

@end

this is our AppDelegate.m

@SauloDesenvolvedor
Copy link

My AppDelegate.m is very similar.

I will continue to look for a solution.

@jjkim0816
Copy link
Author

jjkim0816 commented Mar 22, 2021

@SauloDesenvolvedor

"apns-push-type": "background" is working on background, but not working on quit.

@mikehardy
Copy link
Collaborator

The template was skipped, so I'm closing this.
I'm guessing missing content-available header in JSON https://github.com/invertase/react-native-firebase/issues?q=is%3Aissue+is%3Aopen+content-available+JSON
Also can turn on -FIRDebugEnabled as a build flag in the scheme to get extra logging
Always test on real device
Always watch the log with that flag enabled
Be very aware that data-only messages are NOT RELIABLE by design in iOS. They are for nice-to-have content refreshes, not for vital things. Use a notification JSON block if you must have delivery

@jjkim0816
Copy link
Author

@mikehardy
Thank you @mikehardy .

We response Json to app, set "content-available : true". on APNS header.

APNS: &messaging.APNSConfig{
	Headers: map[string]string{
		"apns-priority":  "5",
	},
	Payload: &messaging.APNSPayload{
		Aps: &messaging.Aps{
			Sound:            "default",
			**ContentAvailable: true**,
		},
	},
},

@Wanderlust-sol
Copy link

Wanderlust-sol commented Mar 23, 2021

@mikehardy
I turned on -FIRDebugEnabled as a build flag with real device.
I sent to push notification in background. and I didn't get any logs...but I always get push notification in background and quit state.
But sometimes I had a different result. For example, I sent a push notification in foreground after that I changed to background mode. Right after I sent a push again, and then I could get logs.
However, after few minutes, I never get any logs again.(but still get push notifications in any state)

2021-03-23 11:53:19.938421+0900 malmoyFrontend[7191:2588086] [connection] nw_socket_handle_socket_event [C42:1] Socket SO_ERROR [54: Connection reset by peer]

2021-03-23 11:53:20.236143+0900 malmoyFrontend[7191:2587661] 7.7.0 - [Firebase/Analytics][I-ACS002002] Engagement timer scheduled to fire in approx. (s): 3600

2021-03-23 11:53:20.506021+0900 malmoyFrontend[7191:2588098] [tcp] tcp_input [C49.1:3] flags=[R] seq=1107526592, ack=0, win=0 state=CLOSED rcv_nxt=1107526592, snd_una=3247047121

2021-03-23 11:53:20.506274+0900 malmoyFrontend[7191:2588098] [tcp] tcp_input [C49.1:3] flags=[R] seq=1107526592, ack=0, win=0 state=CLOSED rcv_nxt=1107526592, snd_una=3247047121

2021-03-23 11:53:21.944809+0900 malmoyFrontend[7191:2566642] dnssd_clientstub write_all(28) DEFUNCT

2021-03-23 11:53:21.945028+0900 malmoyFrontend[7191:2566642] dnssd_clientstub deliver_request ERROR: write_all(28, 50 bytes) failed

2021-03-23 11:53:21.945266+0900 malmoyFrontend[7191:2566642] dnssd_clientstub write_all(28) DEFUNCT

2021-03-23 11:53:30.434771+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS002003] Engagement timer canceled

2021-03-23 11:53:30.435406+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS002002] Engagement timer scheduled to fire in approx. (s): 3600

2021-03-23 11:53:30.435513+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS002003] Engagement timer canceled

2021-03-23 11:53:30.437422+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS023051] Logging event: origin, name, params: auto, user_engagement (_e), {
    engagement_time_msec (_et) = 10197;
    ga_event_origin (_o) = auto;
    ga_screen_class (_sc) = UIViewController;
    ga_screen_id (_si) = 7606704004885397564;
}
2021-03-23 11:53:30.440318+0900 malmoyFrontend[7191:2588166] 7.7.0 - [Firebase/Analytics][I-ACS023073] Debug mode is enabled. Marking event as debug and real-time. Event name, parameters: user_engagement (_e), {
    engagement_time_msec (_et) = 10197;
    ga_debug (_dbg) = 1;
    ga_event_origin (_o) = auto;
    ga_realtime (_r) = 1;
    ga_screen_class (_sc) = UIViewController;
    ga_screen_id (_si) = 7606704004885397564;
}

2021-03-23 11:53:30.459256+0900 malmoyFrontend[7191:2587664] 7.7.0 - [Firebase/Analytics][I-ACS023072] Event logged. Event name, event params: user_engagement (_e), {
    engagement_time_msec (_et) = 10197;
    ga_debug (_dbg) = 1;
    ga_event_origin (_o) = auto;
    ga_realtime (_r) = 1;
    ga_screen_class (_sc) = UIViewController;
    ga_screen_id (_si) = 7606704004885397564;
}

2021-03-23 11:53:30.462772+0900 malmoyFrontend[7191:2587664] 7.7.0 - [Firebase/Analytics][I-ACS002002] Measurement timer scheduled to fire in approx. (s): 0.9646008014678955

2021-03-23 11:53:30.463977+0900 malmoyFrontend[7191:2587664] 7.7.0 - [Firebase/Analytics][I-ACS023051] Logging event: origin, name, params: auto, app_background (_ab), {
    ga_event_origin (_o) = auto;
    ga_screen_class (_sc) = UIViewController;
    ga_screen_id (_si) = 7606704004885397564;
}

2021-03-23 11:53:30.465479+0900 malmoyFrontend[7191:2587664] 7.7.0 - [Firebase/Analytics][I-ACS023073] Debug mode is enabled. Marking event as debug and real-time. Event name, parameters: app_background (_ab), {
    ga_debug (_dbg) = 1;
    ga_event_origin (_o) = auto;
    ga_realtime (_r) = 1;
    ga_screen_class (_sc) = UIViewController;
    ga_screen_id (_si) = 7606704004885397564;
}

2021-03-23 11:53:30.472897+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS023072] Event logged. Event name, event params: app_background (_ab), {
    ga_debug (_dbg) = 1;
    ga_event_origin (_o) = auto;
    ga_realtime (_r) = 1;
    ga_screen_class (_sc) = UIViewController;
    ga_screen_id (_si) = 7606704004885397564;
}

2021-03-23 11:53:30.477948+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS023105] Event is not subject to real-time event count daily limit. Marking an event as real-time. Event name, parameters: user_engagement (_e), {
    engagement_time_msec (_et) = 10197;
    ga_debug (_dbg) = 1;
    ga_event_origin (_o) = auto;
    ga_realtime (_r) = 1;
    ga_screen_class (_sc) = UIViewController;
    ga_screen_id (_si) = 7606704004885397564;
}

2021-03-23 11:53:30.478195+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS023105] Event is not subject to real-time event count daily limit. Marking an event as real-time. Event name, parameters: app_background (_ab), {
    ga_debug (_dbg) = 1;
    ga_event_origin (_o) = auto;
    ga_realtime (_r) = 1;
    ga_screen_class (_sc) = UIViewController;
    ga_screen_id (_si) = 7606704004885397564;
}

2021-03-23 11:53:30.480556+0900 malmoyFrontend[7191:2587664] 7.7.0 - [Firebase/Analytics][I-ACS023087] User property set. Name, value: lifetime_user_engagement (_lte), 3569927

2021-03-23 11:53:30.481293+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS023087] User property set. Name, value: session_user_engagement (_se), 1087261

2021-03-23 11:53:30.486059+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS012018] Saving bundle. size (bytes): 497

2021-03-23 11:53:30.487637+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS023116] Bundle added to the upload queue. BundleID, timestamp (ms): 33, 1616468010427

2021-03-23 11:53:30.492073+0900 malmoyFrontend[7191:2588165] 7.7.0 - [Firebase/Analytics][I-ACS023039] Measurement data sent to network. Timestamp (ms), data: 1616468010491, <APMPBMeasurementBatch: 0x2820f2660>

2021-03-23 11:53:30.495502+0900 malmoyFrontend[7191:2587664] 7.7.0 - [Firebase/Analytics][I-ACS900000] Uploading data. Host: https://app-measurement.com/a

2021-03-23 11:53:30.642929+0900 malmoyFrontend[7191:2588166] 7.7.0 - [Firebase/Analytics][I-ACS901006] Received SSL challenge for host. Host: https://app-measurement.com/a

2021-03-23 11:53:30.728103+0900 malmoyFrontend[7191:2587664] 7.7.0 - [Firebase/Analytics][I-ACS023044] Successful upload. Got network response. Code, size: 204, -1

2021-03-23 11:53:30.738431+0900 malmoyFrontend[7191:2588166] 7.7.0 - [Firebase/Analytics][I-ACS002003] Measurement timer canceled

2021-03-23 11:53:30.738531+0900 malmoyFrontend[7191:2588166] 7.7.0 - [Firebase/Analytics][I-ACS023142] Cancelling background upload task. Task ID : 172
//second case(randomly)
2021-03-23 14:09:44.268211+0900 malmoyFrontend[7407:2639980] App was in Background
2021-03-23 14:09:44.268483+0900 malmoyFrontend[7407:2639980] 제발: {
    Nick = 888fffaafff;
    aps =     {
        alert =         {
            body = "\Ud83d\Ude07fff\Ud83d\Ude42";
            title = "\Uc571\Ub054!!!";
        };
        "content-available" = 1;
        "mutable-content" = 1;
        sound = default;
    };
    "fcm_options" =     {
        image = "https://menu.mt.co.kr/moneyweek/thumb/2018/12/10/06/2018121007208016111_1.jpg";
    };
    "gcm.message_id" = 1616476183968135;
    "google.c.a.e" = 1;
    string = 1112;
}
2021-03-23 14:09:44.286974+0900 malmoyFrontend[7407:2647908] 7.7.0 - [Firebase/Messaging][I-FCM018001] Device has capacity 244037 MB with 2337 MB free.
2021-03-23 14:09:44.287093+0900 malmoyFrontend[7407:2647908] 7.7.0 - [Firebase/Messaging][I-FCM006000] Received message missing local start time, dropped.
2021-03-23 14:09:44.287159+0900 malmoyFrontend[7407:2647908] 7.7.0 - [Firebase/Messaging][I-FCM006000] Received message missing local start time, dropped.
2021-03-23 14:09:44.287358+0900 malmoyFrontend[7407:2647908] 7.7.0 - [Firebase/Messaging][I-FCM016004] Added sync message to cache: 1616476183968135
2021-03-23 14:09:52.892627+0900 malmoyFrontend[7407:2640169] [javascript] 'ios', 'Message handled in the background!', { messageId: '1616476183968135',
  data: 
   { fcm_options: { image: 'https://menu.mt.co.kr/moneyweek/thumb/2018/12/10/06/2018121007208016111_1.jpg' },
     Nick: '888fffaafff',
     string: '1112' },
  contentAvailable: true,
  mutableContent: true,
  notification: { ios: {}, title: '앱끔!!!', sound: 'default', body: '😇fff🙂' } }
2021-03-23 14:09:52.935804+0900 malmoyFrontend[7407:2648823] notifier request success


@mikehardy
Copy link
Collaborator

iOS restricts thing pretty seriously. Make sure your battery is charged, make sure background refresh is on for the app (so you can "background refresh" your "content" which is now "available", right? that's the point of the feature) make sure the phone isn't overheating, make sure you are not in low power mode etc. And it will work sometimes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help: needs-triage Issue needs additional investigation/triaging. type: bug New bug report
Projects
None yet
Development

No branches or pull requests

4 participants