react-native-firebase icon indicating copy to clipboard operation
react-native-firebase copied to clipboard

No Push Notification in iOS

Open husnaingoldev opened this issue 8 years ago • 33 comments

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.

husnaingoldev avatar May 22 '18 06:05 husnaingoldev

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.

husnaingoldev avatar May 22 '18 07:05 husnaingoldev

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

cristianonescu avatar May 22 '18 07:05 cristianonescu

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

husnaingoldev avatar May 22 '18 07:05 husnaingoldev

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

cristianonescu avatar May 22 '18 08:05 cristianonescu

can you show me your code?

or upload it some where so i may download it

husnaingoldev avatar May 22 '18 08:05 husnaingoldev

@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

cristianonescu avatar May 22 '18 09:05 cristianonescu

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

husnaingoldev avatar May 22 '18 09:05 husnaingoldev

@husnaingoldev see my updated comment

cristianonescu avatar May 22 '18 09:05 cristianonescu

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 avatar May 22 '18 09:05 husnaingoldev

@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,
  },
});

cristianonescu avatar May 22 '18 09:05 cristianonescu

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

husnaingoldev avatar May 22 '18 09:05 husnaingoldev

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

but still nothing for ios :(

cristianonescu avatar May 22 '18 09:05 cristianonescu

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

husnaingoldev avatar May 22 '18 09:05 husnaingoldev

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

husnaingoldev avatar May 22 '18 09:05 husnaingoldev

I have the same problem, nothing happened on iOS

alextorn avatar May 22 '18 09:05 alextorn

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

husnaingoldev avatar May 22 '18 09:05 husnaingoldev

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

cristianonescu avatar May 22 '18 09:05 cristianonescu

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

alextorn avatar May 22 '18 09:05 alextorn

@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

husnaingoldev avatar May 22 '18 09:05 husnaingoldev

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

husnaingoldev avatar May 22 '18 10:05 husnaingoldev