Notifications

How to receive push notifications for the chat within your app

Push notifications are a crucial way to engage with your users. This guide will walk you through integrating and setting up push notifications for your app.

How it works:

  • For Android: Brand Messenger sends its payload to Android servers, which then send the push notification to your user's device.
  • For iOS: Brand Messenger sends its payload to Apple servers which then sends the Push notification to your user's device.

Setup

For Android

Refer to this link to Set up your FCM v1 keys and share the required details with Khoros support.,

For iOS

  • Refer to this link to set up APNs tokens and share the required details with Khoros support
  • Next, to update the capabilities of your project, check this link

Set Push Notification Device Token with Brand Messenger SDK

You can manage push notification device tokens with the Brand Messenger SDK.

  • For Android, provide the FCM push notification token.
  • For iOS, provide the APNs push notification token.

Use the following code snippet to add or update the push notification token:

BrandmessengerSdk.addPushNotificationTokenToBrandmessenger(token, (error: null | string, response: null | string) => {
  if (error !== null) {
      console.log('Error registering Push Notification Token :', error)
  } else {
      console.log('Push Notification Token successfully registered on chat backend:', response)
  }
});

Trigger Brand Messenger Notification

For Android:

To trigger a Brand Messenger notification on Android, use a remote notification JSON string payload.

You can check if the notification belongs to the Brand Messenger SDK by utilizing the following function:

const JSONPayload = JSON.stringify(remoteMessage)

BrandmessengerSdk.isBrandMessengerPushNotification(JSONPayload, (error: null | string, isBrandMessengerPushNotification: null | string) => {
  if (error !== null) {
     // Handle error in checking isBrandMessengerPushNotification
     return
  }
  if (isBrandMessengerPushNotification == 'true') {
      // It is a Brand Messenger Push Notification
      BrandmessengerSdk.triggerBrandMessengerNotification(JSONPayload);
  } else {
       // Not a Brand Messenger Push Notification
  }
});

For iOS:

To trigger a Brand Messenger notification on iOS, add the following code to your index.js file to listen for push notifications and an APNs token update callback.

// Add this imports
import BrandmessengerSdk from 'react-native-brandmessenger-sdk';
import { NativeEventEmitter } from 'react-native';

const nativeEventEmitter = new NativeEventEmitter(BrandmessengerSdk);

// Listen for push notification
nativeEventEmitter.addListener('receivedRemoteNotification', (payload) => {
  console.log('Received a APNs Message JSON payload:', payload);
  BrandmessengerSdk.isBrandMessengerPushNotification(payload, (error, isBrandMessengerPushNotification) => {
    if (error !== null) {
      console.log('Error checking the isBrandMessengerPushNotification in IOS:', error)
      return
    }
    if (isBrandMessengerPushNotification == 'true') {
       BrandmessengerSdk.triggerBrandMessengerNotification(payload);
    }
  })
});

// APNs token update to chat backend
nativeEventEmitter.addListener('remoteNotificationDeviceToken', (apnsDeviceTokenPayload) => {
  console.log('APNs device token payload:', apnsDeviceTokenPayload);
  if (Platform.OS === 'ios') {
     const jsonObject = JSON.parse(apnsDeviceTokenPayload);
     const apnsDeviceToken = jsonObject.deviceToken;
     if (apnsDeviceToken) {
       BrandmessengerSdk.addAPNsTokenToBrandmessenger(apnsDeviceToken, (error, response) => {
         if (error !== null) {
           console.log('Error registering in IOS:', error)
         } else {
           console.log('iOS APNs token successfully registered on chat backend:', response)
         }
       })
     }
   }
});

Goto /ios/YourApp/Classes and open the AppDelegate.m file, compare and add the code below in the file:

#import <BrandMessengerCore/BrandMessengerCore.h>
#import <React/RCTBridge.h>
#import "BrandMessengerUI/BrandMessengerUI.h"
#import <UserNotifications/UserNotifications.h>
  
/// Add this UNUserNotificationCenterDelegate in your Appdelegate file
@interface AppDelegate () <UNUserNotificationCenterDelegate>
 
@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  
  // For APNs push notification
  UNUserNotificationCenter.currentNotificationCenter.delegate = self;
  [BrandMessengerManager application:application didFinishLaunchingWithOptions:launchOptions];
  
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

// Emmiting the data to react-native
- (void)sendEventWithName:(NSString *)name withBody:(NSDictionary *)userInfo {
  NSError *error;
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:0 error:&error];
  if (jsonData) {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    if (jsonString) {
      [self.bridge enqueueJSCall:@"RCTDeviceEventEmitter"
                          method:@"emit"
                            args:@[name, jsonString]
                      completion:NULL];
    } else {
      NSLog(@"Failed to convert JSON data to string");
    }
  }
}
// APNs token sending to react-native
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  NSMutableString *deviceTokenString = [NSMutableString stringWithCapacity:(deviceToken.length * 2)];
  const unsigned char *dataBuffer = (const unsigned char *)[deviceToken bytes];
  for (int i = 0; i < deviceToken.length; ++i) {
    [deviceTokenString appendFormat:@"%02x", dataBuffer[i]];
  }
  
  NSDictionary *deviceTokenInfo = @{@"deviceToken": deviceTokenString};
  [self sendEventWithName:@"remoteNotificationDeviceToken" withBody:deviceTokenInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  KBMPushNotificationService *pushNotificationService = [[KBMPushNotificationService alloc] init];
  if ([pushNotificationService isBrandMessengerChatNotification:userInfo]) {
    [self sendEventWithName:@"receivedRemoteNotification" withBody:userInfo];
  }
  completionHandler(UIBackgroundFetchResultNewData);
}
// UNUserNotificationCenterDelegate methods
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
  NSDictionary *userInfo = notification.request.content.userInfo;
  
  KBMPushNotificationService *pushNotificationService = [[KBMPushNotificationService alloc] init];
  if ([pushNotificationService isBrandMessengerChatNotification:userInfo]) {
    [self sendEventWithName:@"receivedRemoteNotification" withBody:userInfo];
  }
  completionHandler(UNNotificationPresentationOptionNone);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler {
  NSDictionary *userInfo = response.notification.request.content.userInfo;
  
  KBMPushNotificationService *pushNotificationService = [[KBMPushNotificationService alloc] init];
  if ([pushNotificationService isBrandMessengerChatNotification:userInfo]) {
    [self sendEventWithName:@"receivedRemoteNotification" withBody:userInfo];
  }
  completionHandler();
}
@end

Implementing [BrandMessengerManager application:application didFinishLaunchingWithOptions:launchOptions]; is required for the SDK to register and respond to events such as network connectivity changes and local banner alerts.

If the implementation forbids making updates to the AppDelegate class, the following can be used instead of adding [BrandMessengerManager application:application didFinishLaunchingWithOptions:launchOptions];.

import BrandmessengerSdk from 'react-native-brandmessenger-sdk';
...

// Add the following to your JS code when the app launches, to run the iOS SDK setup code.
BrandmessengerSdk.appLaunchSetupBypass();

Modules

In the scenario where you have a setup where multiple app modules exist in a single Brand Messenger application instance, you need to set your app code to the correct module with the following:

import BrandmessengerSdk from 'react-native-brandmessenger-sdk';
...
BrandmessengerSdk.setAppModuleName("AnotherModuleName");