React-native-fcm: FCM.presentLocalNotification not working on iOS

Created on 13 Dec 2016  ·  64Comments  ·  Source: evollu/react-native-fcm

rn 39.2
rn-fcm: 2.5.2
iOS 10.1

The below method is not working on iOS 10.1, it does not show a local notification when the app is in foreground:

RCT_EXPORT_METHOD(presentLocalNotification:(id)data resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
  if([UNUserNotificationCenter currentNotificationCenter] != nil){
    UNNotificationRequest* request = [RCTConvert UNNotificationRequest:data];
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
      if (!error) {
        resolve(nil);
      }else{
        reject(@"notification_error", @"Failed to present local notificaton", error);
      }
    }];
  }else{
    UILocalNotification* notif = [RCTConvert UILocalNotification:data];
    [RCTSharedApplication() presentLocalNotificationNow:notif];
    resolve(nil);
  }
}

However if I go back to the older code that it is only:

    UILocalNotification* notif = [RCTConvert UILocalNotification:data];
    [RCTSharedApplication() presentLocalNotificationNow:notif];
    resolve(nil);

it works fine

how can I add logs on native code to debug properly this? or add a breaking point?

cc @MechanicKim had the same issue

All 64 comments

I've added some logs on the code

RCTLogWarn(@"PPP %@", [UNUserNotificationCenter currentNotificationCenter]);

RCTLogWarn(@"PPP1: %@", data);
RCTLogWarn(@"PPP2: %@", request);

I've noticed that request has the following format:

YellowBox.js:69 PPP2: <UNNotificationRequest: 0x17422aea0; identifier: 1481659752360, content: <UNNotificationContent: 0x1742e3d00; title: (null), subtitle: (null), body: Blue comentou no seu post: "Lucas ", categoryIdentifier: brandlovers.LIKE, launchImageName: , peopleIdentifiers: (
), threadIdentifier: , attachments: (
), badge: (null), sound: <UNNotificationSound: 0x1700ab6a0>, hasDefaultAction: YES, shouldAddToNotificationsList: YES, shouldAlwaysAlertWhileAppIsForeground: NO, shouldLockDevice: NO, shouldPauseMedia: NO, isSnoozeable: NO, fromSnooze: NO, darwinNotificationName: (null), darwinSnoozedNotificationName: (null), trigger: <UNCalendarNotificationTrigger: 0x17403d8c0; dateComponents: <NSDateComponents: 0x174151930>
    Calendar Year: 2016
    Month: 12
    Leap month: no
    Day: 13
    Hour: 18
    Minute: 9
    Second: 12, repeats: NO>>

I guess that shouldAlwaysAlertWhileAppIsForeground: NO should be true to be able to show the notification while the app is in foreground

@sibelius it is fixed in 2.5.2 please verify
where is shouldAlwaysAlertWhileAppIsForeground?

shouldAlwaysAlertWhileAppIsForeground is this variable: UNNotificationRequest* request

result of UNNotificationRequest* request = [RCTConvert UNNotificationRequest:data];

interesting. I don't see it in my xcode intellisense. Are you sure it is an exposed property?

I'm not sure

I just add a RCTLogWarn(@"PPP2: %@", request); to print it on chrome debug

idk if this helps

it could be a private property

I got the same problem and tried to go back to older code.

FCM.presentLocalNotification isn't still working on iOS

I can confirm this :(

@VinZenTz1989 @yannickoo are you using the latest version?

@evollu yes I'm using 2.5.2. I'm logging incoming (remote & local) notifications and I can even see them in my Xcode console but local notifications don't appear on 📱 .

what is the error message? Can you try adding id: 'some id' into payload?

I also tried it with id property but IIRC you added that in fb9a3bf3d9023a6b81d2e659b41026df356ad260 😕

One question I always had: Where could I find a correct implementation in AppDelegate.m because I saw different implementations and the code from the README.md seems to be incomplete because things like settings the APNS token or telling Firebase that user opened notification is missing.
Is there chance that local notifications could not work because there is some code missing in AppDelegate.m?

read me is correct. Setting APNS token is done by FCM SDK automatically.
Are you seeing local notification not showing up or red screen?

No red screen there is just no change in the UI.

BTW the reason why I did integrate the APNS token: I always got Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)" (#229) in Xcode console and the solution for that was setting the token.

fixed in 2.5.3

@evollu I guess this should be enough right? Still not seeing local notifications in foreground :(

FCM.presentLocalNotification({
  body: 'body',
  show_in_foreground: true
})

Thanks for your fast responses ❤️

have you rebuilt ios?

Wow nice I could get a local notification! Unfortunately it's not showing up when adding sound property.

what sound value are you passing

I tried notification and notification.wav (one of them worked in the past) and the audio file is properly referenced in Ressources.

is there any error in xcode log?

There is only <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)" but this shouldn't be relevant for this issue.

does it work if you comment out line 250-259

Magic :dizzy: I can hear the custom notification sound again :)

ok so it works for old API but not new one?

Exactly. I'm using iOS 10.2 btw

there must be a way, let me check

can you replace line 48 with

NSString* sound = [RCTConvert NSString:details[@"sound"]];
  if(sound != nil){
    content.sound = [UNNotificationSound soundNamed:sound];
  }

try both with and w/o sound property and see if both work correctly

Does not work when using the current implementation at line ~250. I guess I need to switch back to your suggestion from https://github.com/evollu/react-native-fcm/issues/226#issuecomment-267678456.

sure you can do the work around. I will play with it myself and figure out the fix.

@yannickoo just played with it. works for me. try 2.5.4

Just updated the 📦 and it works!

@evollu sorry for replying late.
Just updated everything works fine.
Thank you for your help

@VinZenTz1989 do you receive remote and background notifications for your app with the latest code?

it does work on the latest branch, tks @evollu for the hard work

however, it is showing 2 notifications instead of just 1

@sibelius I don't have this issue. Do you have more detail?

this is my function to handle push notification, appLink will go to screen based on url deeplinking

export function handlePush(notif) {
  if (!notif) {
    return;
  }

  if(notif.local_notification) {
    //this is a local notification
    console.log('local notification: ', notif.local_notification)

    if (notif.opened_from_tray) {
      // Cancel notification
      FCM.cancelLocalNotification(notif.id);
      if (notif.url) {
        appLink(notif.url, navigator);
      }
    }

    return;
  }

  if(notif.opened_from_tray) {
    //app is open/resumed because user clicked banner
    console.log('opened_from_tray: ', notif.opened_from_tray)
    if (notif.url) {
      appLink(notif.url, navigator);
    }
    return;
  }

  const userInteraction = AppState.currentState === 'background';
  if (userInteraction) {
    if (notif.url) {
      appLink(notif.url, navigator);
    }
  } else {
    console.log('presentLocal');
    FCM.presentLocalNotification({
      id: new Date().getTime().toString(),
      title: notif.title,
      body: notif.body,
      url: notif.url,
      icon: 'ic_notification',
      large_icon: 'ic_notification',
      color: '#e34056',
      priority: 'high',
      auto_cancel: false,
      click_action: 'brandlovers.LIKE',
      show_in_foreground: true,
      // priority: "high",
    })
  }
}

If you pass show_in_foreground in push notification body, you don't need to call presentLocalNotification manually.

this notification come from my backend, so I can't have show_in_foreground in the push notification body, because I don't know if the user will have the app opened or not, so if the app is in foreground I create a local notification from the remote notification

when you say you see 2 notifications, are they both remote? or one is local?

A receive a remote notification that do not show up in the tray neither for the user,
this remote notification will create a local notification, after that

this line will be called twice:
console.log('local notification: ', notif.local_notification)

so it is not notification showed twice, but the callback gets called twice? are you using iOS?

this only happens on ios, on android the behavior is correctly

can you add break point in AppDelegate.m on both onLocalNotificationReceive and willReceiveNotification? I suspect both of them are called

@evollu should we implement willReceiveNotification? It's not specified in the README file yet if so.

oh I mean willPresentNotification

onLocalNotificationReceived is didReceiveLocalNotification ?

This is the flow when the app is on foreground on ios

  • receive remote notification
  • handlePush: localNotification: false (gcm.message_id: 0:1482235706845068%58fc5f4058fc5f40)
  • calls willPresentNotification: show_in_foreground is false, so call completionHandler(UNNotificationPresentationOptionNone);
  • handlePush: localNotification: false (yep, again: gcm.message_id: 0:1482235706845068%58fc5f4058fc5f40, the same as above)
  • calls willPresentNotification: show_in_foreground is true, so call completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound);
  • handlePush: localNotification: true
  • handlePush: localNotification: true

I think the flow is kind of confusing, feel free to ask more information

didReceiveLocalNotification has not been called

@sibelius ah, can you check if didReceiveRemoteNotification is called first?
add if([UNUserNotificationCenter currentNotificationCenter] != nil){ return; } in line 71 in AppDelegate.m

I cannot get any notification to show up when the app is in foreground. When I try to present a local notification, I can log it, but no banner is shown, and nothing shows up in the Notification Center.
I also tried to send show_in_foreground: true from the server, but the notification still didn't show up, when the app is running in foreground. Everything works as expected when the app is in background.

Any ideas what the issue could be?

Here's the code for the local notification:

FCM.presentLocalNotification({
  title: notif.title,
  body: notif.body,
  priority: "high",
  local: true,
  data: notif.data
});

@stefanwuest what is your payload on server side?

This is my payload on the server side:

$fields = array(
            'to' => $deviceToken,
            'collapse_key' => 'new_message',
            'data' => [
                'custom_notification' => [
                    'title' => 'Test',
                    'body' => $messageTxt,
                    'sound' => 'default',
                    'data' => $custom,
                    'show_in_foreground' => true
                ]
            ],
            'notification' => [
                'title' => 'Test',
                'body' => $messageTxt,
                'sound' => 'default',
                'data' => $custom,
                'show_in_foreground' => true
            ]
        );

I had a same experience.
But I could resolve this problem. For resolving this problem.

  • Update version
  • Please refer readme and fix android setting.
    Android setting for using this service has been changed.
  • Test local notification!

I succeed through this process.
I hope that my recommendation will help you.

Good luck!

2017-01-05 15:14 GMT+09:00 stefanwuest notifications@github.com:

This is my payload on the server side:

$fields = array(
'to' => $deviceToken,
'collapse_key' => 'new_message',
'data' => [
'custom_notification' => [
'title' => 'Test',
'body' => $messageTxt,
'sound' => 'default',
'data' => $custom,
'show_in_foreground' => true
]
],
'notification' => [
'title' => 'Test',
'body' => $messageTxt,
'sound' => 'default',
'data' => $custom,
'show_in_foreground' => true
]
);


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/evollu/react-native-fcm/issues/226#issuecomment-270571972,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ALlkF-y_2DHXVj6e1xXolr41_MBEwx8Cks5rPIo2gaJpZM4LMJmh
.

@stefanwuest are you trying to target both platform? If so you can't do it with custom_notification.
try this.
```
//ios
'to' => $deviceToken,
'data' => [
'show_in_foreground' => true
],
'notification' => [
'title' => 'Test',
'collapse_key' => 'new_message',
'body' => $messageTxt,
'sound' => 'default',
'data' => $custom
]

//android
'to' => $deviceToken,
'data' => [
'custom_notification' => [
'title' => 'Test',
'body' => $messageTxt,
'sound' => 'default',
'data' => $custom,
'show_in_foreground' => true
]
]

@evollu yes, trying to target both platforms. the problem is now on iOS when the app is in foreground. I tried your suggested payload, but still no success.
I can log the notification, but no banner showing up, and nothing is in notification center.
image

when you are in foreground, notification are sent through FCM socket rather than APN (it is a firebase behavior), which means you need to build a local notification specifically.
To verify that, you can add break points in notification handlers in AppDelegate.m and nothing should be triggered

I was not able to have a local notification show up (see my first post in this issue).
Here's the call for that again:

FCM.presentLocalNotification({
  title: notif.title,
  body: notif.body,
  priority: "high",
  local: true,
  data: notif.data
});
FCM.presentLocalNotification({
  title: notif.title,
  body: notif.body,
  priority: "high",
  show_in_foreground: true,
  data: notif.data
});

Got it. Seems like my notif.title and notif.body was undefined. Thanks for the help!

aha...
@sibelius can I close this now?

yep, I'll reopen if needed

hey i am getting same problem

i am manually triggering this
FCM.presentLocalNotification({ vibrate: 500, title: "Hello", body: "Test Notification", big_text: "i am large, i am large, i am large, i am large,", show_in_foreground: true, number: 10 });
its working in android but not in ios why???

@chitaranjanxelpmoc check your notification permission

You're correct.Thanks it solved.

Was this page helpful?
0 / 5 - 0 ratings