React-native-firebase: No Push Notification in iOS

Created on 22 May 2018  路  33Comments  路  Source: invertase/react-native-firebase

import firebase from 'react-native-firebase';
import type, { RemoteMessage, Notification, NotificationOpen } from 'react-native-firebase';


import { Platform } from 'react-native';

export class MyPushNotification {

getInitialNotification = (navigate) => {


        firebase.notifications().getInitialNotification()
            .then((notificationOpen) => {

                if (notificationOpen) {

                    console.log("initial notification", notificationOpen);
                    // App was opened by a notification
                    // Get the action triggered by the notification being opened
                    // const action = notificationOpen.action;
                    // Get information about the notification that was opened
                    // const notification = notificationOpen.notification;
                    this.openThreadNow(notificationOpen, navigate);
                }
            });

}



onComponentDidMount = () => {

        this.notificationListener = firebase.notifications().onNotification((notification) => {
            // Process your notification as required
            console.log("notification received", notification);

        });
}

onComponentWillMount = () => {

        this.messageListener = firebase.messaging().onMessage((message) => {
            // Process your message as required

            console.log("message received", message);
        });
}



getToken = (is_push_enabled, server_type) => {

        firebase.messaging().getToken().then(fcmToken => {
            if (fcmToken) {
                console.log("fcmTokenfcmToken", fcmToken);
                this.savePushTokenToServer(fcmToken, server_type);
            } else {
                console.log("no token found");
            }
        });
}


initPushService = (server_type, is_push_enabled, navigate) => {

    this.my_navigator = navigate;
    try {
        firebase.messaging().requestPermission()
            .then(() => {

                this.getToken(is_push_enabled, server_type);
            })
            .catch(error => {
                console.log("user rejected the permission");
            });
    } catch (e) {
        console.log("eeeeeeeee", e);
    }
}

}

this is my code for Push Notification Class, i am calling it from a class component like follwoing

push_service;

constructor(props) {
    super(props);
    this.push_service = new MyPushNotification();
}

componentWillMount() {

    this.push_service.onComponentWillMount()

}


componentDidMount() {
      this.push_service.initPushService("test1", true, this.props.navigation);
      this.push_service.onComponentDidMount();
      this.push_service.getInitialNotification(this.props.navigation);

}

and this is the code for AppDelegate.m

#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

#import <Firebase.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary     *)launchOptions
{
  [FIRApp configure];
  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                  moduleName:@"MyFirebase"
                                           initialProperties:nil
                                               launchOptions:launchOptions];
  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];

  [RNFirebaseNotifications configure];

  return YES;
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
  [[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
  [[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
  [[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}

@end

background remote notification works in android but not in iOS, i am testing on iOS 10.3.3

if the app is in foreground whenever i send a new push notification from Firebase console, i see a console with this line
console.log("message received", message);

and when app is killed or in background no notification appears in the notifications center, and if i open the app ty tapping the app icon, this same line executes again
console.log("message received", message);

Please help in this issue, i am stuck in it for days.

Most helpful comment

Hi, this worked for me.
just put this in didFinishLaunchingWithOptions inside AppDelegete.m

//////////////////////  PUSH NOTIFICATION PERMISSIONS /////////////////////////////////
  UIUserNotificationSettings *settings =
  [UIUserNotificationSettings
   settingsForTypes: (UIUserNotificationTypeBadge |
                      UIUserNotificationTypeSound |
                      UIUserNotificationTypeAlert)
   categories:nil];

  [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

  // Register the supported interaction types.

  UIUserNotificationType types = UIUserNotificationTypeBadge |

  UIUserNotificationTypeSound | UIUserNotificationTypeAlert;

  UIUserNotificationSettings *mySettings =

  [UIUserNotificationSettings settingsForTypes:types categories:nil];

  [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];



  // Register for remote notifications.

  [[UIApplication sharedApplication] registerForRemoteNotifications];

//////////////////////////////////////////////////////////////////////////

and then rebuild your app. and test it on the device. now it will ask for push notifications permissions.

All 33 comments

ok so i have solved this above problem. but now there is another issue, when i receive push notification if app is killed, then by tapping the notification apps opens but getInitialNotification gets executed unlimited times, i am navigating from one screen to other, so it keeps on navigating to the second screen forever, i have to kill the app to stop this behaviour.

How did you solved the first problem? I also don't receive notifications on IOS, android works fine.

@cristianonescu make sure your AppDelegate is same as mine. Then do check following things.

1) GoogleService-Info.plist is in the project directory.
2) Navigate to Capabilities tab(just besides with General tab) and check Push notifications are switch on, and in Background Modes Remote Notifications is checked.
3) Your POD should look like this
platform :ios, '9.0'

target 'APP_NAME' do
 pod 'Firebase/Core', '~> 4.13.0'
 pod 'Firebase/Messaging
end

run pod update

If all this is fine, then uninstall the app from iphone and reinstall and try again.
Let me know if i can help you further.

Thanks.

Still can't make it work :(
I'm sending the notification, and nothing comes for IOS.. just android

can you show me your code?

or upload it some where so i may download it

@husnaingoldev
this is the App.js >> https://pastebin.com/NCqLsMur

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';

import firebase from 'react-native-firebase';
import type, { RemoteMessage, Notification, NotificationOpen } from 'react-native-firebase';


const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

const notification = new firebase.notifications.Notification()
  .setNotificationId('notificationId')
  .setTitle('My notification title')
  .setBody('My notification body')
  .setData({
    key1: 'value1',
    key2: 'value2',
  });


// // Build a channel
// const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)
// .setDescription('My apps test channel');

// // Create the channel
// firebase.notifications().android.createChannel(channel);

type Props = {};
export default class App extends Component<Props> {

  componentDidMount() {

    firebase.messaging().hasPermission()
    .then(enabled => {
      if (enabled) {
        // user has permissions
        this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
          // Process your notification as required
          // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
          onNotification = (notification: Notification) => {
            notification.android.setChannelId(notification.data.channelId);
            firebase.notifications().displayNotification(notification);
          };
        });
        this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
            // Process your notification as required
        });

        this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
          // Get the action triggered by the notification being opened
          const action = notificationOpen.action;
          // Get information about the notification that was opened
          const notification: Notification = notificationOpen.notification;
      });

      firebase.notifications().getInitialNotification()
      .then((notificationOpen: NotificationOpen) => {
        if (notificationOpen) {
          // App was opened by a notification
          // Get the action triggered by the notification being opened
          const action = notificationOpen.action;
          // Get information about the notification that was opened
          const notification: Notification = notificationOpen.notification;  
        }
      });

      } else {
        // user doesn't have permission
        firebase.messaging().requestPermission()
        .then(() => {
          // User has authorised
          this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
            // Process your notification as required
            // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
          });
          this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
              // Process your notification as required
          });
        })
        .catch(error => {
          // User has rejected permissions  
        });
      } 
    });
}

componentWillUnmount() {
  this.notificationDisplayedListener();
  this.notificationListener();
  this.notificationOpenedListener();
}

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <TouchableOpacity
          style={{backgroundColor: 'cyan'}}
          onPress={()=>{
            firebase.notifications().displayNotification(notification);
            // firebase.auth()
            //   .signInAnonymouslyAndRetrieveData()
            //   .then(credential => {
            //     if (credential) {
            //       console.log('default app user ->', credential.user.toJSON());
            //     }
            //   });
          }}>
          <Text>Test</Text>
        </TouchableOpacity>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

this is the AppDelegate.m >> https://pastebin.com/MaznqcU2

#import "AppDelegate.h"
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"
#import <Firebase.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [FIRApp configure];
  [RNFirebaseNotifications configure];
  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"EverseenMobileRN"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  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];
  return YES;
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
  [[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
  [[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
  [[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}

@end

And these are the capabilities:
screen shot 2018-05-22 at 12 02 12

these links are not accesible, i am unable to open these links

@husnaingoldev see my updated comment

Use it like following

componentDidMount() {
 this.notificationListener = firebase.notifications().onNotification((notification) => {
            // Process your notification as required
            console.log("notification received", notification);
        });


firebase.notifications().getInitialNotification()
        .then((notificationOpen) => {
            if (notificationOpen) {


                // console.log("initial notification", notificationOpen);
                // App was opened by a notification
                // Get the action triggered by the notification being opened
                // const action = notificationOpen.action;
                // Get information about the notification that was opened
                // const notification = notificationOpen.notification;
                    this.openThreadNow(notificationOpen, navigate);
            }
        });
}



componentWillMount() {

       this.messageListener = firebase.messaging().onMessage((message) => {

            console.log("message received", message);
        });
}

Try these and see if you get any thing in the console.

@husnaingoldev

my App.js looks now like this.. and nothing

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';

import firebase from 'react-native-firebase';
import type, { RemoteMessage, Notification, NotificationOpen } from 'react-native-firebase';


const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

const notification = new firebase.notifications.Notification()
  .setNotificationId('notificationId')
  .setTitle('My notification title')
  .setBody('My notification body')
  .setData({
    key1: 'value1',
    key2: 'value2',
  });

type Props = {};
export default class App extends Component<Props> {

  componentWillUnmount() {
    this.notificationDisplayedListener();
    this.notificationListener();
    this.notificationOpenedListener();
  }

  componentDidMount() {
    this.notificationListener = firebase.notifications().onNotification((notification) => {
      // Process your notification as required
      console.log("notification received", notification);
    });


    firebase.notifications().getInitialNotification()
      .then((notificationOpen) => {
        if (notificationOpen) {


          // console.log("initial notification", notificationOpen);
          // App was opened by a notification
          // Get the action triggered by the notification being opened
          // const action = notificationOpen.action;
          // Get information about the notification that was opened
          // const notification = notificationOpen.notification;
          this.openThreadNow(notificationOpen, navigate);
        }
      });
  }

  componentWillMount() {

    this.messageListener = firebase.messaging().onMessage((message) => {

      console.log("message received", message);
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <TouchableOpacity
          style={{ backgroundColor: 'cyan' }}
          onPress={() => {
          }}>
          <Text>Test</Text>
        </TouchableOpacity>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

keep the app open, send a push notification from firebase console, and then see if you can see any thing in console?

your code displays on android:
screen shot 2018-05-22 at 12 40 23

but still nothing for ios :(

this is my app js
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* 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/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

#import <Firebase.h>
#import "RNFirebaseNotifications.h"
#import "RNFirebaseMessaging.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  [FIRApp configure];
  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"RNFire"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  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];

  [RNFirebaseNotifications configure];

  return YES;
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
  [[RNFirebaseNotifications instance] didReceiveLocalNotification:notification];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
  [[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
  [[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings];
}

@end

and this is App.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';


import firebase from 'react-native-firebase';
import type, { RemoteMessage, Notification, NotificationOpen } from 'react-native-firebase';




const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});


export default class App extends Component {

  componentWillMount() {

    this.notificationListener = firebase.notifications().onNotification((notification) => {
      // Process your notification as required
      console.log("notification received", notification);

    });

    this.messageListener = firebase.messaging().onMessage((message) => {
      // Process your message as required

      console.log("message received", message);
    });
  }

  componentWillUnmount() {
    this.notificationListener();
    this.messageListener();
    this.notificationOpenedListener();
  }

  componentDidMount() {

    firebase.messaging().hasPermission()
      .then(enabled => {
        if (enabled) {
          // user has permissions

          this.getToken();

        } else {
          console.log("User do not have permission for Push notification");
          this.askPermission()
        }
      });

    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
      // Get the action triggered by the notification being opened
      const action = notificationOpen.action;
      // Get information about the notification that was opened
      const notification = notificationOpen.notification;

      console.log(notificationOpen);
    });

    firebase.notifications().getInitialNotification()
      .then((notificationOpen) => {
        if (notificationOpen) {
          console.log("firebase initial notification",notificationOpen);
          // App was opened by a notification
          // Get the action triggered by the notification being opened
          const action = notificationOpen.action;
          // Get information about the notification that was opened
          const notification = notificationOpen.notification;
        }
      });
  }

  askPermission = () => {
    firebase.messaging().requestPermission()
      .then((permission) => {
        console.log("permissionpermission", permission);

        this.getToken();
      })
      .catch(error => {
        console.log("user rejected the permission");
      });
  }

  getToken = () => {

    firebase.messaging().getToken().then(fcmToken => {


      if (fcmToken) {
        console.log("fcmTokenfcmToken", fcmToken);
      } else {
        console.log("no token found");
      }
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

i have just tested in it my iphone i received notification

and make sure you are testing push notification on a real iPhone, because remote push notifications do not work on simulators.

I have the same problem, nothing happened on iOS

@alextorn you are not getting remote push notification or getInitialNotification keeps on executing?

@husnaingoldev
Copy pasted your above code... and still nothing for ios :(

@husnaingoldev i'm not getting push notifications. I did manual linking, because react-native link react-native-firebase failed.

@cristianonescu i have just tested this code, and it works fine.

double check your POD

platform :ios, '9.0'

target 'YOUR_APP_NAME' do


  # Pods for RNFire
  pod 'Firebase/Core', '~> 4.13.0'
  pod 'Firebase/Messaging'


end

run pod install

and do react-native link react-native-firebase

if it is not working, then i am not sure what is wrong with your code base

@alextorn follow all the steps i mentioned above, and see if you can receive any thing in the console.

@husnaingoldev and @alextorn
Hello again, I found a solution to my problem and now everything works!

It was an issue with certificates and keys that nowhere is described well... so I found this guy and followed his steps of this video: https://www.youtube.com/watch?v=HRocERqesHA

For eveybody in the future:
just get the above code that @husnaingoldev provided and then follow the above video to generate and use the certificates.

@cristianonescu i already use authentication key. And it's setup properly.

@husnaingoldev @cristianonescu Did you guys add any code to AppDelegate.h file?

@alextorn nope. mine looks like this:

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

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (nonatomic, strong) UIWindow *window;

@end

I'm closing this as the initial issue appears to be resolved, and the rest is just conversation about misconfiguration. Please feel free to carry on the conversation, but as it's not an issue with React Native Firebase it doesn't need to remain open.

Hi, this worked for me.
just put this in didFinishLaunchingWithOptions inside AppDelegete.m

//////////////////////  PUSH NOTIFICATION PERMISSIONS /////////////////////////////////
  UIUserNotificationSettings *settings =
  [UIUserNotificationSettings
   settingsForTypes: (UIUserNotificationTypeBadge |
                      UIUserNotificationTypeSound |
                      UIUserNotificationTypeAlert)
   categories:nil];

  [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

  // Register the supported interaction types.

  UIUserNotificationType types = UIUserNotificationTypeBadge |

  UIUserNotificationTypeSound | UIUserNotificationTypeAlert;

  UIUserNotificationSettings *mySettings =

  [UIUserNotificationSettings settingsForTypes:types categories:nil];

  [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];



  // Register for remote notifications.

  [[UIApplication sharedApplication] registerForRemoteNotifications];

//////////////////////////////////////////////////////////////////////////

and then rebuild your app. and test it on the device. now it will ask for push notifications permissions.

@yashojha19 it is worked thanks a lot. But i'm little bit confused about why this information not mentioned in documentation @chrisbianca? I guess [[UIApplication sharedApplication] registerForRemoteNotifications]; is the key for this issue.

Hello Guys! turns out there is a better way of doing this.
https://rnfirebase.io/docs/v4.3.x/messaging/receiving-messages
this url is enough but for further explanation :
so i did something like this in my splash screen

  componentDidMount() {

    firebase.messaging().hasPermission()
  .then(enabled => {
    // user has permissions
    if (enabled) {

      // notification listener if app is opened through notification
      firebase.notifications().getInitialNotification().then(notificationOpen => {
        console.log("notification initial",notificationOpen)

        if(notificationOpen && notificationOpen.notification && notificationOpen.notification._data ){
          const not_data = JSON.parse(notificationOpen.notification._data.data)
          this.loginThroughNotification(not_data);
        }
        else{
          this.loginNormally();
        }  
      });

    // if user not has permissions: ask for permissions
    } else {
            firebase.messaging().requestPermission()
            .then(() => {
              // User has authorised  
              this.loginNormally();
            })
            .catch(error => {
              this.loginNormally();
              // User has rejected permissions  
            });
   } 
  });
  }

i am facing the same problem, funny thing is it work well before and i don't know why it not working right now. I try to use all suggest above.

Any help pls?

What does the error say for you?

I faced the same problem in the past days. It worked well on Android devices but not working in iOS.
Finally I resolved it by following below links:

https://medium.com/@paul.allies/react-native-firebase-cloud-messaging-ios-97b59e5f28ec
https://www.youtube.com/watch?v=HRocERqesHA

Especially the video, it tells details that I missed.

@nomoneylee
Exactly Bro. It worked for me too. Specially the video. Thank you

// Register for remote notifications.

[[UIApplication sharedApplication] registerForRemoteNotifications];

Thanks @yasoza

Did the trick for me, but this line of code is nowhere to be found in the documentation of react-native-firebase. I am a but confused what this line of code is doing. Because it is not asking for permissions, (that's good, because in js code you can ask permission when you feel like it's the right time to bother the enduser). It magically make sure that the received notifications are handled by the OS to be displayed in the notifications center and to receive the notifications via the listeners in your js code.

Was this page helpful?
0 / 5 - 0 ratings