Skip to content

Not receiving notifications when app is closed IOS #306

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

Closed
darkcoderrises opened this issue Aug 3, 2017 · 29 comments
Closed

Not receiving notifications when app is closed IOS #306

darkcoderrises opened this issue Aug 3, 2017 · 29 comments
Labels
plugin: messaging FCM only - ( messaging() ) - do not use for Notifications

Comments

@darkcoderrises
Copy link

darkcoderrises commented Aug 3, 2017

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"
}

@chrisbianca
Copy link
Contributor

chrisbianca commented Aug 4, 2017

@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?

@darkcoderrises
Copy link
Author

@chrisbianca No I am not receiving.

@chrisbianca
Copy link
Contributor

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

@darkcoderrises
Copy link
Author

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.

@chrisbianca
Copy link
Contributor

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

@darkcoderrises
Copy link
Author

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

@Jobeso
Copy link

Jobeso commented Aug 5, 2017

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',
      })

@darkcoderrises
Copy link
Author

darkcoderrises commented Aug 6, 2017

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?

@Jobeso
Copy link

Jobeso commented Aug 6, 2017

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',})

@darkcoderrises
Copy link
Author

@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.

@morgerardo
Copy link

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

@sonnn
Copy link

sonnn commented Oct 5, 2017

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?

@kevando
Copy link

kevando commented Oct 24, 2017

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

@chrisbianca chrisbianca added the plugin: messaging FCM only - ( messaging() ) - do not use for Notifications label Nov 1, 2017
@chrisbianca
Copy link
Contributor

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 #595 for updates.

@esutton
Copy link

esutton commented Nov 8, 2017

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.

@rajeshzmoke
Copy link

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?

@chrisbianca
Copy link
Contributor

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

@shubham1164
Copy link

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

@SilvioLuis
Copy link

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

@Linoa65
Copy link

Linoa65 commented Sep 11, 2019

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.

@Linoa65
Copy link

Linoa65 commented Sep 18, 2019

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

@dody87
Copy link

dody87 commented Feb 4, 2020

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.

@atultiwaree
Copy link

Hey any update guys I'm not getting any console log when app is closed in background notification listener though notification appears

@mikehardy
Copy link
Collaborator

@atultiwaree when discussing firebase messaging, always include the JSON you were sending to the FCM REST API to trigger the behavior

My guess is you using a notification block - the underlying firebase-ios-sdk posts a visible local notification in this case but does not wake up your app, no handlers are called unless / until the user interacts with the notification (then. you should be able to use react-native's notification opened app handler, and perhaps the onMessage handler))

@atultiwaree
Copy link

atultiwaree commented Feb 17, 2024

@atultiwaree when discussing firebase messaging, always include the JSON you were sending to the FCM REST API to trigger the behavior

My guess is you using a notification block - the underlying firebase-ios-sdk posts a visible local notification in this case but does not wake up your app, no handlers are called unless / until the user interacts with the notification (then. you should be able to use react-native's notification opened app handler, and perhaps the onMessage handler))

@mikehardy thanks for replay you're right when I sent payload with notifications key it didn't triggered "onBackground event" instead when I sent only data it triggered, actually in Android I was able to see when background notification came and waked my app in background but in iOS I was not able after killing app I was not getting any log in xcode

I'll be more than happy if you please suggest me some debugger and debugging tips for iOS because terminal works well in Android but not in iOS and flipper is also their for Android but not able to use in iOS because of firebase

I confirmed weather background event fired in iOS or not using AsyncStorage 😄

@mikehardy
Copy link
Collaborator

So with iOS data only is not reliable. You ha e to use a notification block. With a notification block your app doesn't get control and the notification is plain. Only way we know around this is notifee.app to do an extension thing that allows skinning the notification at least

@atultiwaree
Copy link

@mikehardy correct with notification payload it shows UI Alert without this it does not show, but using notifee + notification data payload it works just fine, mine problem is I'm not able to get logs when my ios app closed in actual device and for single change I've to re run the app but in android everything just works fine even flipper in iOS I can't even use flipper, please suggest me some solution debugging setup ? so that I can handle background process of app like mutating storage etc.

@mikehardy
Copy link
Collaborator

mikehardy commented Feb 18, 2024

Console.app with device plugged in or xsimctl can view device logs. Use console.log in your app with strings that are easy to filter on. Flipper is going away in react-native anyway based on upstream discussion. Not having it is not a big deal.

@atultiwaree
Copy link

@mikehardy Thank-You for your help, you're right instead of flipper I've found reactotron for debugging it worked just fine though JS Logs are still logging in flipper,
what worked for me is I connected my compueter and iOS device with same wifi and shaked my phone and cliked on open debugger and I was able to get logs even after the app was closed whenever background event fired after arrival of notification 🙂

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

No branches or pull requests