React-native-firebase: Not receiving notifications when app is closed IOS

Created on 3 Aug 2017  路  22Comments  路  Source: invertase/react-native-firebase

I have an app which uses react-native-firebase. I followed the initialisation steps provided for installing the app and for cloud messaging. Now when I use firebase console to send notification to a single user (haven't tried sending to a bunch, but I guess result would be the same), I receive the notification if the app is open, otherwise not. I read somewhere that when app is closed, one doesn't receive notification in the code, rather user see's a notification in notification bar and when clicked on, it invokes getInitialNotification().

  1. Target Platform : iOS
  2. Development Operating System: macOS Sierra
  3. Build tools: Xcode 8.2.1
  4. React Native version 0.45.1
  5. RNFirebase Version 2.0.4

Podfile:

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'FroogalMerchant' do
  pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga"
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'BatchedBridge', 
    'Core',
    'RCTText',
    'RCTWebSocket',
    'RCTNetwork',
  ]

  pod 'Firebase/Core'
  pod 'RNFirebase', :path => '../node_modules/react-native-firebase'  

  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'

  target 'FroogalMerchantTests' do
    inherit! :search_paths
    # Pods for testing
  end

end

Notification Listener component

import React, {Component} from 'react'
import {View, Platform} from 'react-native'
import firebase from '../utils/Firebase.js'

export default class NotificationListener extends Component {
  componentWillMount() {
    firebase.messaging().onMessage((message) => console.log('message', message));
    // This gets logged only when the app is open
    // Nothing happens when app is closed, no notification is shown either


    firebase.messaging().getInitialNotification()
      .then((notification) => {
        console.log('Notification which opened the app: ', notification);
      });
    // This is never called
  }

  render() {
    return (
      <View style={{width: '100%', height: '100%'}}>
        {this.props.children}
      </View>
    );
  }
}

Notification I am sending:

{
"registration_ids" : [""],
"notification": {
"title" : "Hi",
"body" : "Heyy"
},
"priority": "high"
}

Messaging

Most helpful comment

Yes,
I got a similar issue. You need to give firebase an authentication certificate in the firebase settings.
For more: See here on firebase .
Another thing you can try is debugging. You can take this code and integrate it, call the screen and then close the app. 10 seconds after this code is executed, it will display a notification which is locally. Just to test you did everything right.

firebase.messaging().scheduleLocalNotification({
        fire_date: new Date().getTime() + 10000, // RN's converter is used, accept epoch time and whatever that converter supports
        id: `123456`, // REQUIRED! this is what you use to lookup and delete notification. In android notification with same ID will override each other
        body: `Your notification body"`,
        title: 'Your title',
      })

All 22 comments

@darkcoderrises Are you seeing the notification popup in the OS whilst the app is closed / in the background? Or are you not receiving this either?

@chrisbianca No I am not receiving.

Have you called firebase.messaging().requestPermissions()? This is required on iOS so that the user gives the app permission to send notifications.

Yeah I call request permission at the start of the app. I receive notifications when app is open, but not when the app is closed.

Have you enabled:
1) The push notifications capability
2) Remote notifications under the background modes capability?

If you're not receiving the notifications when in the background, this is a setup issue with FCM, not with react-native-firebase

Yeah, I have enabled them both. Is there anything else that is required for me to configure for background notifications?

Yes,
I got a similar issue. You need to give firebase an authentication certificate in the firebase settings.
For more: See here on firebase .
Another thing you can try is debugging. You can take this code and integrate it, call the screen and then close the app. 10 seconds after this code is executed, it will display a notification which is locally. Just to test you did everything right.

firebase.messaging().scheduleLocalNotification({
        fire_date: new Date().getTime() + 10000, // RN's converter is used, accept epoch time and whatever that converter supports
        id: `123456`, // REQUIRED! this is what you use to lookup and delete notification. In android notification with same ID will override each other
        body: `Your notification body"`,
        title: 'Your title',
      })

I am getting the local notification and I have followed the procedure as in the link provided. But I still can't receive notification when it is closed.
@Jobeso any other suggestion?

maybe there is a problem with this:

{
"registration_ids" : [""],
"notification": {
"title" : "Hi",
"body" : "Heyy"
},
"priority": "high"
}

Sending a message from your api should look like this:

firebase.messaging().sendToDevice(notificationId, {notification: {title: 'hey', body: 'test',},}, {priority: 'high',})

@chrisbianca @Jobeso I receive the notification in the objective-c code (AppDelegate.m).

`

  • (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo {
    NSLog(@"%@", userInfo);
    NSLog(@"%id", application.applicationState);
    NSLog(@"userinfo->%@", [userInfo objectForKey:@"aps"]);

[RNFirebaseMessaging didReceiveRemoteNotification:userInfo];
}

  • (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
    fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
    NSLog(@"%@", userInfo);
    NSLog(@"%id", application.applicationState);
    NSLog(@"userinfo->%@", [userInfo objectForKey:@"aps"]);

    [RNFirebaseMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
    }`

from where it is supposed to be passed to rn firebase messaging. I think that is the point when it should create a notification.

Any luck solving this? i'm having the same issue

I have the same issue with this and what i did to solve is put this code request for permission after [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self]; and before return YES

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        // iOS 7.1 or earlier. Disable the deprecation warnings.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        UIRemoteNotificationType allNotificationTypes =
        (UIRemoteNotificationTypeSound |
         UIRemoteNotificationTypeAlert |
         UIRemoteNotificationTypeBadge);
        [application registerForRemoteNotificationTypes:allNotificationTypes];
#pragma clang diagnostic pop
    } else {
        // iOS 8 or later
        // [START register_for_notifications]
        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
            UIUserNotificationType allNotificationTypes =
            (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
            UIUserNotificationSettings *settings =
            [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        } else {
            // iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
            // For iOS 10 display notification (sent via APNS)
            [UNUserNotificationCenter currentNotificationCenter].delegate = self;
            UNAuthorizationOptions authOptions =
            UNAuthorizationOptionAlert
            | UNAuthorizationOptionSound
            | UNAuthorizationOptionBadge;
            [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
            }];
#endif
        }

        [[UIApplication sharedApplication] registerForRemoteNotifications];
        // [END register_for_notifications]
    }

https://github.com/firebase/quickstart-ios/blob/master/messaging/MessagingExample/AppDelegate.m

This comes from firebase quickstart iOS and same with requestPermission. Notice both are successful asking permission. But requestPermission cannot receive notification when app close. Not sure why. Can anyone look into this?

For me I fixed this by adding my cert to the firebase web console.

But I am wondering where is all the documentation for this? Is this everything???
https://rnfirebase.io/docs/v3.0.*/messaging/reference/messaging#onTokenRefresh

Thanks for reporting. We're aware of lots of issues with notifications and will be addressing them all as part of the v3.2.0 release stream. Please see https://github.com/invertase/react-native-firebase/issues/595 for updates.

Question

Should a closed app be capable of displaying a notification sent Monday, when the user launches the app Friday, for example?

Currently I can:

1) Send and display a notification in iOS if app is in foreground
2) Send and display a notification in iOS when app is closed,
only IF user presses open notification on the iOS notification's home screen.

I am not clear if I should be able to display notifications when app is opened, if user ignored or did not see the the initial home screen notification.

Badges I do not understand at all. I was hoping a badge would display if user did not see a notification sent when app was closed.

Tips and suggestions much appreciated.

im not able to get foreground notification ...background notification works

constructor(props) {
super(props);
messaging.requestPermissions();
messaging.getToken().then(token => {
this.setState({ fcm_token: token });
//update your fcm token on server.
// console.log('====================================');
console.log(' token', this.state.fcm_token);
// console.log('====================================');
});
messaging.onMessage(payload => {
if (payload.local_notification) return;
console.log('Message received. ', payload);
messaging.createLocalNotification({
...payload.fcm,
local_notification: true, // prevent loop
show_in_foreground: true,
priority: 'high'
});
if (Platform.OS === 'ios') {
console.log('ios present notification');
messaging.scheduleLocalNotification({
...payload.aps,
fire_date: new Date().getTime() + 1000, // in 1 sec
id: Unique id ${Date.now()},
soundName: 'default',
show_in_foreground: true,
priority: 'high'
});
}
});

Android it works for both cases but in ios foreground notification isnt working any help?

Good news, the long awaited alpha of our messaging and notifications overhaul is now available!!

Check out the release notes here: https://github.com/invertase/react-native-firebase/releases/tag/v4.0.0-alpha.1

If you have any comments and suggestions or want to report an issue, come find us on Discord

How to receive data-only push from FCM on IOS when the app is closed? There is no info regarding the data-only message handler in IOS when the app is closed. Please advice something

I'm having the same problem. data-only messages do not arrive when my app is closed.

Same here for IOS

App foreground : Notification received
App background : Notification received
App closed : Nothing happens

There is a workaround to make it works ? Because we need to use local notifications to display data, we cannot use remote notification.

@chrisbianca There is a solution to handle data-only message when app is closed on IOS ?

Hi, we have the same issue, however we noted that in the first install of the app, the notifications on iOS work for background. Unfortunately, after the app is closed, not just the notifications didn't come when it's closed, also when you open the app again nothing happens which any kind of notifications.

What could be wrong? or what should I'm missing on it?

Thanks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Damnum picture Damnum  路  3Comments

alizahid picture alizahid  路  3Comments

dgruseck picture dgruseck  路  3Comments

ODelibalta picture ODelibalta  路  3Comments

romreed picture romreed  路  3Comments