Configuring push notifications (React Native)

Configuring Firebase


Google Firebase Cloud Messaging is necessary to handle push notifications sent from Synerise.

  1. Follow the instructions in this article.
  2. Integrate the Firebase project with Synerise. See this article.

Setting up - Android


Requirements

After configuring Firebase, add the google-services.json file to your project/android/app catalog.

Firebase Cloud Messaging integration

  1. Add the google-services dependency to your project’s build.gradle file.

      dependencies {
              ...
              classpath 'com.google.gms:google-services:4.3.3'
              ...
          }
      

  2. Configure the application’s build.gradle as follows:

      dependencies {
          implementation fileTree(dir: "libs", include: ["*.jar"])
          implementation "com.facebook.react:react-native:+"  // from node_modules
    
          // FCM
          implementation "com.google.firebase:firebase-messaging:20.0.1"
          implementation "com.google.android.gms:play-services-base:17.1.0"
          implementation "com.google.firebase:firebase-core:17.2.1"
          implementation "com.google.firebase:firebase-analytics:17.2.1"
              ...
          }
      

  3. Make sure that at the end of the application gradle file, you add plugin: ‘com.google.gms.google-services’

  4. In your MainApplication class, include setPushListener to listen for the changes of the Firebase token.

    @Override
      public void onCreate() {
        super.onCreate();
        SoLoader.init(this, /* native exopackage */ false);
        getReactNativeHost().getReactInstanceManager().createReactContextInBackground();
    
        RNNotifications.setPushListener(new OnRegisterPushListener() {
    
          @Override
          public void onRegisterPushRequired() {
            FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(instanceIdResult -> {
              String refreshedToken = instanceIdResult.getToken();
              Log.d(TAG, "Refreshed token: " + refreshedToken);
    
              RNNotifications.setRegistrationToken(refreshedToken);
            });
          }
        });
      }
    

Receiving push notifications

In order to handle Synerise push notifications, you must pass the incoming push payload to the Synerise SDK.

  1. Create a class extending FirebaseMessagingService:
    public class MyFirebaseMessagingService extends FirebaseMessagingService {
    
        private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
    
        @Override
        public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
            super.onMessageReceived(remoteMessage);
            Map<String, String> data = remoteMessage.getData();
            RNNotifications.onNotificationReceive(data);
        }
    
        @Override
        public void onNewToken(String refreshedToken) {
            super.onNewToken(refreshedToken);
    
            Log.d(TAG, "Refreshed token: " + refreshedToken);
    
            if (refreshedToken != null) {
                RNNotifications.setRegistrationToken(refreshedToken);
            }
        }
    }
      
  2. To enable banners, handle the intent when the app starts. You can do it in your MainActivity by calling RNNotifications.onNotificationReceive in your onCreate and onNewIntent.
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            RNNotifications.onNotificationReceive(getIntent().getExtras());
        }
    
        @Override
        public void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
            RNNotifications.onNotificationReceive(intent.getExtras());
        }
      

Setting up - iOS


Requirements

Configure handling Push Notifications in your application. See Apple Notifications.

Firebase Cloud Messaging integration

  1. Import RNNotifications.h

       import react-native-synerise-sdk
       

  2. Extend the Firebase Messaging Delegate so our SDK can receive the Firebase token that is required to deliver push notifications from Synerise.

       func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
    
        if #available(iOS 10, *) {
          UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
    
          }
        } else {
          let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
          application.registerUserNotificationSettings(settings)
        }
    
        application.registerForRemoteNotifications()
       }
    
       // MARK: - MessagingDelegate
    
       func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        RNNotifications.didChangeRegistrationToken(fcmToken)
       }
       

    Important: Make sure that the Firebase token is always up-to-date. When it changes, use RNNotifications.didChangeRegistrationToken(registrationToken:) again.

Receiving push notifications

The following code shows how to receive push notifications in the AppDelegate.h and pass these to the React Native part of the application:

Important: To properly receive notifications, all of these methods must be implemented.
// iOS 9
// Push Notifications
// Silent Push Notifications

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  RNNotifications.didReceiveNotification(userInfo)
  completionHandler(.noData)
}

func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) {
  RNNotifications.didReceiveNotification(userInfo, actionIdentifier:identifier)
  completionHandler()
}

// iOS 10 and above
// Push Notifications

// MARK: - UNUserNotificationCenterDelegate

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  RNNotifications.didReceiveNotification(response.notification.request.content.userInfo, actionIdentifier:response.actionIdentifier)
  completionHandler()
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  RNNotifications.didReceiveNotification(notification.request.content.userInfo)
  completionHandler(UNNotificationPresentationOptions.init(rawValue: 0))
}

Extensions for push notifications

Notification Service Extension

Synerise Notification Service Extension is an object that adds the notification functionality to the SDK.

It implements the following operations:

  • Decrypting Simple Push communication data (if encryption is enabled).
  • Tracking events from Simple Push communication.
  • Adding action buttons to Simple Push communication (if the communication contains any).
  • Improving the appearance of Simple Push communication (Rich Media - Single Image) with an image thumbnail.

Notification Service Extension should be implemented in the native part of the application. Follow the instructions in this article.

Rich Media Notification Content Extensions

Synerise Rich Media Notification Content Extension is an object that allows rendering your own appearance of a push notification when the notification is expanded (by tapping the notification).

Synerise Rich Media Notification Content Extensions should be implemented in the native part of the application. Follow the instructions in this article.

Set up Firebase FCM token registration for Synerise SDK


Get Firebase FCM token from the native part of the application so our SDK can receive the Firebase token that is required to deliver push notifications from Synerise. Make sure that the Firebase FCM token is always up-to-date by implementing the onRegistrationRequired() method.

Synerise.Notifications.setListener({
  onRegistrationToken: function(token) {
    Synerise.Notifications.registerForNotifications(token, true, function() {
      // success
    }, function(error) {
      // failure
    });
  },
  onRegistrationRequired: function() {
    let registrationToken = getLastPushRegistrationToken();
    let mobilePushAgreement = true; // true or false, should depend on device permissions and customer's agreement in the application

    Synerise.Notifications.registerForNotifications(registrationToken, mobilePushAgreement, function() {
      // success
    }, function(error) {
      // failure
    });
  }
  //...
});
Important: The second parameter of the registration method is the agreement for mobile push campaigns. In the Profile’s card in Synerise, you can find it in the Subscriptions section (if you have the required access permission). Learn more about the Synerise.Notifications.registerForNotifications(registrationToken:mobilePushAgreement:onSuccess:onError:) method in the method reference.
Important: You must always keep the Firebase token updated. In many cases in the application lifecycle, such as authorization, destroy session, user context change, and so on, the registration needs to be updated. In these situations, the SDK invokes the onRegistrationRequired() method (see code snippet above).

Configure Notification Encryption


Android

See Configure Notification Encryption.

iOS

See Synerise Notification Service Extension and Configure Notification Encryption.

Application implementation

In the application, you must set encryption to true in the SDK initializer or in the SDK settings.

// The first way
// WARNING: This option must be configured before Synerise SDK is initialized!
Synerise.Settings.notifications.encryption = true;

// The second way
Synerise.Initializer()
  .withClientApiKey('XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX')
  .withBaseUrl(null)
  .withDebugModeEnabled(true)
  .withCrashHandlingEnabled(true)
  .withSettings({
    notifications: {
      enabled: true,
      encryption: true
    }
    //...
  })
  .init()

Handling incoming push notifications


Note: You may disable handling push notifications in the SDK at any time. See Enable/disable notifications.

Synerise payload

The following code shows how to handle push notifications:

Synerise.Notifications.setListener({
  //...
  onNotification: function(payload, actionIdentifier) {
    if (Synerise.Notifications.isSyneriseNotification(payload)) {
      Synerise.Notifications.handleNotification(payload, actionIdentifier);
    }
  }
  //...
});

Custom payload

You may send both custom push notifications and custom campaigns in Synerise. The code below of one sample delegate method checks the notification origin and then handles it.

Synerise.Notifications.setListener({
  //...
  onNotification: function(payload, actionIdentifier) {
    if (Synerise.Notifications.isSyneriseNotification(payload)) {
      Synerise.Notifications.handleNotification(payload, actionIdentifier);
    } else {
      // Handle other notification in your own way
    }
  }
  //...
});

Encrypted payloads

If you handle the Synerise notification, you do not have to do anything. The SDK decrypts Synerise notification’s payload:

Otherwise, if it is a custom encrypted push notification sent by Synerise, or you need decrypt data from the push notification, there are two methods for dealing with it:

Synerise.onReady(function() {
    //...
    onNotification: function(payload, actionIdentifier) {
      if (Synerise.Notifications.isSyneriseNotification(payload)) {
        let isNotificationEncrypted = Synerise.Notifications.isNotificationEncrypted(payload)
        var decryptedPayload
        if (isNotificationEncrypted) {
          decryptedPayload = Synerise.Notifications.decryptNotification(payload)
        } else {
          decryptedPayload = payload
        }
        Synerise.Notifications.handleNotification(decryptedPayload, actionIdentifier)
      }
    }
    //...
  })
})
Note: The Synerise.Notifications.decryptNotification(payload) method returns raw data when the payload is not encrypted. If the operation fails, the method returns null.

Handling actions from push notifications


Additional in-app alert from push notifications


The React Native SDK on iOS devices can display an additional alert in the application after a push notification is received. See this article to read more about this feature.

Simple Push campaign with in-app alert
Simple Push campaign with in-app alert

Limitations compared to native platforms


Due to platform limitations, not all notification functionalities may work as in native SDKs.

😕

We are sorry to hear that

Thank you for helping improve out documentation. If you need help or have any questions, please consider contacting support.

😉

Awesome!

Thank you for helping improve out documentation. If you need help or have any questions, please consider contacting support.

Close modal icon Placeholder alt for modal to satisfy link checker