Android


1. Firebase Setup


If you have firebase account for your application you can skip this step. If you do not have a Firebase account for your application, refer https://firebase.google.com/docs/android/setup and create an account for you application.


2. Freshchat FCM key configuration

  1. In Firebase Console Under your project go to cloud messaging tab and you will see your Server Key, copy that. 
  2. In Freshchat web portal, paste your Server Key under Settings > Mobile SDK.


3. Add Android Project to Firebase


  1. Click Add Firebase to your Android app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
  2. When prompted, enter your app's package name. It's important to enter the package name your app is using; this can only be set when you add an app to your Firebase project.
  3. During the process, you'll download a google-services.json file. You can download this file again at any time.
  4. Add rules to your root-level build.gradle file, to include the google-services plugin and the Google's Maven repository,


buildscript {
      // ...
      dependencies {
          // ...
          classpath 'com.google.gms:google-services:4.2.0' // google-services plugin
      }
  }
 
  allprojects {
      // ...
      repositories {
          // ...
          google() // Google's Maven repository
      }
  }


     v. Then, in your module Gradle file (usually the app/build.gradle), add the apply plugin line at the bottom of the file to enable the                 Gradle plugin,


apply plugin: 'com.android.application'
  android {
      // ...
    }
    dependencies {
      // ...
      implementation 'com.google.firebase:firebase-core:16.0.6'
      // Getting a "Could not find" error? Make sure you have
      // added the Google maven respository to your root build.gradle
    }
    // ADD THIS AT THE BOTTOM
    apply plugin: 'com.google.gms.google-services'



After you add the initialization code, run your app to send verification to the Firebase console that you've successfully installed Firebase.


4. Receiving push token

You need to create FirebaseMessagingService.java


To use FirebaseMessagingService, you need to add the following code in your app manifest,


<span style="font-size: 14px;"><span style="font-family: Helvetica Neue;"><service android:name=".java.MyFirebaseMessagingService">
      <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
  </service>

</span></span>


Push token will be received in onNewToken function of FirebaseMessagingService class. 


Refer https://firebase.google.com/docs/cloud-messaging/android/client#monitor-token-generation for more details.


On receiving the push token, you can pass it to Freshchat using the below snippet.


Freshchat.getInstance(context).setPushRegistrationToken(token);


5. Receiving push notification and passing to React native freshchat SDK


By overriding the method onMessageReceived() in FirebaseMessagingService, you can access the push notification payload.


Use the below snippet to pass the receive payload to React native freshchat SDK. Add it to FirebaseMessagingService.java


import com.facebook.react.bridge.WritableMap;
  import com.facebook.react.bridge.WritableNativeMap;
  import java.util.Map;
  import com.facebook.react.ReactApplication;
  import com.facebook.react.ReactInstanceManager;
  import com.facebook.react.bridge.ReactApplicationContext;
  import com.facebook.react.bridge.ReactContext;
  import com.facebook.react.modules.core.DeviceEventManagerModule;

  @Override
      public void onMessageReceived(RemoteMessage remoteMessage) {
        if (Freshchat.isFreshchatNotification(remoteMessage)) {
              Freshchat.getInstance(this).handleFcmMessage(this,remoteMessage);
              final WritableMap params = new WritableNativeMap();
        for(Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
            params.putString(entry.getKey(), entry.getValue());
        }

        ReactInstanceManager mReactInstanceManager = ((ReactApplication) getApplication()).getReactNativeHost().getReactInstanceManager();
        ReactContext context = mReactInstanceManager.getCurrentReactContext();

        ((ReactApplicationContext) context)
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit("notification_payload", params);  
          } else {
              //Handle notifications for app
          }
      }


Add below code in index.js


import { DeviceEventEmitter } from 'react-native';

  var freshchatNotificationConfig = new FreshchatNotificationConfig();
  freshchatNotificationConfig.priority = FreshchatNotificationConfig.NotificationPriority.PRIORITY_HIGH;
  freshchatNotificationConfig.notificationSoundEnabled = false;
  Freshchat.setNotificationConfig(freshchatNotificationConfig);

  const fromPushNotifications = (pushPayload) => {
    console.log(pushPayload);
    Freshchat.isFreshchatNotification(pushPayload, (fromFreshchat) => {
          console.log('isFreshchatNotification:', fromFreshchat);
          if (fromFreshchat) {
              console.log('handlePushNotification triggered');
              Freshchat.handlePushNotification(pushPayload);
          } else {
              // handle your app notification
          }
      })
  };

  DeviceEventEmitter.addListener('notification_payload', fromPushNotifications);


iOS


1. Push Notification p12 Certificate creation and uploading to Freshchat

    

Refer https://support.freshchat.com/support/solutions/articles/232534.


2. Enabling Push Notification capabilities


Go to capabilities section of your Xcode project and enable Push Notification feature. 


3. UserNotifiications Framework setup


i. Import UserNotifications framework inside your Appdelegate class.

    

ii. Make your Appdelegate class conforms to UNUserNotificationCenterDelegate protocol and add the following code inside     

        application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions [UIApplicationLaunchOptionsKey: Any]?) -> Bool function,

    UNUserNotificationCenter.current().delegate = self

    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }

    UIApplication.shared.registerForRemoteNotifications()

    

iii. Implement the following methods of the UNUserNotificationCenterDelegate protocol in Appdelegate class:

    * func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) - To handle Push notification click event.

    * func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) - To pass the device token generated from the device.


4. Passing Device token to Freshchat


The following function will get executed after user gives permission for Push Notification, then pass the device token back to Freshchat SDK.


func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        Freshchat.sharedInstance().setPushRegistrationToken(deviceToken)

    }


5. Handling push notification click on app killed state


Add the following line under application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool function,

    

if Freshchat.sharedInstance().isFreshchatNotification(launchOptions) {

            Freshchat.sharedInstance().handleRemoteNotification(launchOptions, andAppstate: application.applicationState)

        }


First check if the notification is from Freshchat, if yes pass the details to Freshchat SDK by calling handleRemoteNotification function.


6. Handling push notification click on app running state


Add the following code to handle push notification click handling when app is in running state,


func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        let dictionary = response.notification.request.content.userInfo

        let appstate = UIApplication.shared.applicationState

        if Freshchat.sharedInstance().isFreshchatNotification(dictionary) {

            Freshchat.sharedInstance().handleRemoteNotification(dictionary, andAppstate: appstate)

        }

    }