react-native-push-notification icon indicating copy to clipboard operation
react-native-push-notification copied to clipboard

How to trigger "onNotification" function on received notification?

Open ArchanaSharma95 opened this issue 6 years ago • 22 comments

my "onNotification" function is not triggered when getting remote notification. I have used the same flow explained inside example app. After logged in inside app how can I call the "onNotification" and how it will trigger every time when remote notification occur?

I have created "NotificationHandler" class where I have called "configure" function and created a NotificationService where I called NotificationHandler inside the constructor.

NotificationService::

import PushNotification from 'react-native-push-notification';
import NotificationHandler from './NotificationHandler';

export default class NotificationService{
  constructor(onRegister, onNotification) {
    this.lastId = 0;
    this.lastChannelCounter = 0;

    this.createDefaultChannels();

    NotificationHandler.attachRegister(onRegister);
    NotificationHandler.attachNotification(onNotification);

    // Clear badge number at start
    PushNotification.getApplicationIconBadgeNumber(function (number) {
      if (number > 0) {
        PushNotification.setApplicationIconBadgeNumber(0);
      }
    });
    
    PushNotification.getChannels(function(channels) {
      console.log(channels);
    });
  }
}

NotificationHandler::

class NotificationHandler {
  onNotification(notification) {
    console.log('NotificationHandler:', notification);

    if (typeof this._onNotification === 'function') {
      this._onNotification(notification);
    }
  }

  onRegister(token) {
    console.log('NotificationHandler:', token);

    if (typeof this._onRegister === 'function') {
      this._onRegister(token);
    }
  }

  onAction(notification) {
    console.log ('Notification action received:');
    console.log(notification.action);
    console.log(notification);

    if(notification.action === 'Yes') {
      PushNotification.invokeApp(notification);
    }
  }

  // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
  onRegistrationError(err) {
    console.log(err);
  }
  
  attachRegister(handler) {
    this._onRegister = handler;
  }

  attachNotification(handler) {
    this._onNotification = handler;
  }
}

const handler = new NotificationHandler();

PushNotification.configure({
  // (optional) Called when Token is generated (iOS and Android)
  onRegister: handler.onRegister.bind(handler),

  // (required) Called when a remote or local notification is opened or received
  onNotification: handler.onNotification.bind(handler),

  // (optional) Called when Action is pressed (Android)
  onAction: handler.onAction.bind(handler),

  // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
  onRegistrationError: handler.onRegistrationError.bind(handler),

  // IOS ONLY (optional): default: all - Permissions to register.
  permissions: {
    alert: true,
    badge: true,
    sound: true,
  },

  // Should the initial notification be popped automatically
  // default: true
  popInitialNotification: true,

  /**
   * (optional) default: true
   * - Specified if permissions (ios) and token (android and ios) will requested or not,
   * - if not, you must call PushNotificationsHandler.requestPermissions() later
   */
  requestPermissions: true,
});

export default handler;

Inside App.js constructor I have created an object of "NotificationService", it's successfully created token and then I logged in inside app and saved token with the user session. Now after user logged in I want to handle the notifications inside my main screen, I called configure() by creating an object of "NotificationService". I am trying to send test messages using a token from fcm but app is not triggering the "onNotification" function. How we can trigger the main configure "onNotification" function when receives notification?

ArchanaSharma95 avatar Oct 08 '20 12:10 ArchanaSharma95

Hi @ArchanaSharma95 You will find more information there: https://github.com/zo0r/react-native-push-notification/blob/master/trouble-shooting.md

On the exemple project, onNotification method of .configure will be called at every moment describe in the link. The onNotification in the component will not be called if the component is not mounted or mounted too late.

You will probably need to store the notification to use it lated.

Regards

Dallas62 avatar Oct 09 '20 06:10 Dallas62

@Dallas62 , I have called this inside main Dashboard component constructor, when sending notification through fcm nothing happened, and currently this component is mounted. I am able to generate the device token but not getting any notification. Even I have tried to add consoles inside my "AppDelegate.m"

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  printf("I called");
  completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}

after this I send fcm test message but "I called" not appears inside xcode console. I am not able to detect the exact issue

ArchanaSharma95 avatar Oct 09 '20 07:10 ArchanaSharma95

If you are using FCM on iOS this will not work. You must use RNFirebase to get an FCM token on iOS, or use the APN services / APIs, or use the firebase API to convert the APN token to a Firebase token.

Dallas62 avatar Oct 09 '20 07:10 Dallas62

@Dallas62, ok I will check this for ios. But similar case is happening for android. I am able to generate the device token but it's not creating a channel and also then onNotification is not triggered. I have used channelExists function to check android channel status, but always gives me "false" value. To create channel I have used same approach used inside example app. Inside "NotificationService" I have called function "this.createDefaultChannels();" inside constructor::

createDefaultChannels() {
		PushNotification.createChannel(
      {
			channelId: 'test-notifications', // (required)
			channelName: 'Test Notifications', // (required)
			channelDescription: 'A main channel to show the notifications on android', // (optional) default: undefined.
			// soundName: 'default', // (optional) See `soundName` parameter of `localNotification` function
			importance: 4, // (optional) default: 4. Int value of the Android notification importance
			vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
			},
			(created) => console.log(`createChannel ${androidNotificationChannelId} returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
		);
}

ArchanaSharma95 avatar Oct 09 '20 07:10 ArchanaSharma95

This method send true when the channel is created or updated, and false in all other cases (already exist, not supported)

Did you specify the default channel for firebase ?

Dallas62 avatar Oct 09 '20 07:10 Dallas62

@Dallas62 , yes I have added default channel, for this I have added this meta tag inside android manifest::

<meta-data
	android:name="com.google.firebase.messaging.default_notification_channel_id"
	android:value="test-notifications" />

ArchanaSharma95 avatar Oct 09 '20 07:10 ArchanaSharma95

What is the payload send to FCM ? Also, is it on simulator ? (Sometimes turning on/off network solve notification issues)

Dallas62 avatar Oct 09 '20 07:10 Dallas62

@Dallas62, No I am using device. And I am not getting what payload you are taking about. I have used latest version of react native firebase(6) and completed android setup, after this I just created a sample notification and send test message from there.

ArchanaSharma95 avatar Oct 09 '20 07:10 ArchanaSharma95

If you are using the FCM Dashboard, you enter in the case of: https://github.com/zo0r/react-native-push-notification/blob/master/trouble-shooting.md#2-noisy-remote-push-notifications

Which will not trigger onNotification expect on notification pressed.

Dallas62 avatar Oct 09 '20 07:10 Dallas62

@Dallas62 but this is case when app is in background, right now I am working on foreground. Even my channel Id is not created and right now app is not receiving any notification. Is there any step by step guide to show notification. I am stuck on a first step, not able to create channel and not receiving any notifications.

ArchanaSharma95 avatar Oct 09 '20 08:10 ArchanaSharma95

Did you see the Channel in the channel list of the Phone ? (settings) or using:

PushNotification.getChannels(function (channel_ids) {
  console.log(channel_ids); // ['channel_id_1']
});

Dallas62 avatar Oct 09 '20 08:10 Dallas62

@Dallas62 , I have refreshed my app and now I am able to see my channel name. After this I send notification from server using fcm but nothing receives inside console(onNotification) function

ArchanaSharma95 avatar Oct 09 '20 09:10 ArchanaSharma95

Can you share the payload used in Firebase to send the notification ?

Dallas62 avatar Oct 09 '20 09:10 Dallas62

@Dallas62 , I'm just sending Test messages, this is a reference screenshot:: https://nimb.ws/nFetMm

ArchanaSharma95 avatar Oct 09 '20 09:10 ArchanaSharma95

Does the token still valid ? Do you receive a notification in the notification center ? (test with this 3 app state: foreground/background/killed)

Dallas62 avatar Oct 09 '20 09:10 Dallas62

@Dallas62, yes I am getting notification in notification center when app in background or killed, but onNotification still not trigger.

ArchanaSharma95 avatar Oct 09 '20 09:10 ArchanaSharma95

Do you see something in the console from this line when the application is in foreground:

    console.log('NotificationHandler:', notification);

There is 3 onNotification in your code, I don't know which one you are talking about.

Dallas62 avatar Oct 09 '20 09:10 Dallas62

@Dallas62 , No nothing is displaying inside console. My console is cleared. And I'm talking about handler function with is bind to show onNotification event(inside configure{}).

ArchanaSharma95 avatar Oct 09 '20 09:10 ArchanaSharma95

Can you share the content of the AndroidManifest ? (Try to keep the whole tree-structure and activity/services, you can remove app name and secrets)

Dallas62 avatar Oct 09 '20 10:10 Dallas62

@Dallas62 ,Yes I can, sorry I was replying so late. Manifest.xml file content::

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.myapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
      android:name="com.myapp.MainApplication"
      android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:allowBackup="false"
        android:largeHeap="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme">
		 <!-- [START fcm_default_channel] -->
		 <meta-data
			 android:name="com.google.firebase.messaging.default_notification_channel_id"
			 android:value="test-notifications" />
		 <!-- [END fcm_default_channel] -->
      <activity
        android:name="com.myapp.MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>
</manifest>

ArchanaSharma95 avatar Oct 14 '20 11:10 ArchanaSharma95