Push Notifications

Configuring Firebase

Google Firebase Cloud Messaging is necessary to handle Mobile Campaigns sent from Synerise.

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

Setting up - iOS

Requirements

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

Firebase Cloud Messaging

  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:

// 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)
  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)
  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))
}
Important: To ensure proper receiving of notifications, all of these methods must be implemented.
Note: You may disable handling Push Notifications in the SDK at any time. See Enable/disable notifications.

Setting up - Android

Requirements

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

Firebase Cloud Messaging

  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'
              ...
          }
      
    Important: Make sure that at the end of application gradle file you add apply plugin: ‘com.google.gms.google-services’
  3. In your MainApplication class, include setPushListener to listen for 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

Documentation on how to prepare push notifications on app.synerise.com is available in our Knowledge Base.

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());
        }
      

Synerise Push Notification payload structure

Each notification follows this basic structure:

{
	"aps": {
		...
	},    
	"issuer": "Synerise",
	"message-type": "dynamic-content",
	"content-type": "template-banner",
	"content": {
	}
}
  • issuer - in Synerise notifications, the issuer is always Synerise.
  • message-type - specifies if the content is static or dynamic.
  • content-type - specifies the type of content in the payload.
  • content - the actual content (for example, in HTML).

Methods such as Synerise.isNotificationSimplePush(_:) let you check if the incoming content is of the expected type.

For more information, see the method reference.

Handling Synerise Push Notifications

The following code shows how to handle push notifications in the React Native part of the application:

Synerise.Notifications.setListener({
  onRegistrationToken: function(token) {
    Synerise.Notifications.registerForNotifications(token, true, function() {
      console.log("Synerise Push Registration is succeed");
    }, function(error) {
      console.log(error.message);
    });
  },
  onRegistrationRequired: function() {
    let registrationToken = getLastPushRegistrationToken();

    Synerise.Notifications.registerForNotifications(registrationToken, true, function() {
      console.log("Synerise Push Registration is succeed");
    }, function(error) {
      console.log(error.message);
    });
  },
  onNotification: function(payload) {
    if (Synerise.Notifications.isSyneriseNotification(payload)) {
      Synerise.Notifications.handleNotification(payload);
    }
  },
});
😕

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.