Configuring push notifications (React Native)
Configuring Firebase
Google Firebase Cloud Messaging is necessary to handle push notifications sent from Synerise.
- Follow the instructions in this article.
- 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
-
Import
RNNotifications.h
import react-native-synerise-sdk
-
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, useRNNotifications.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, 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))
}
Setting up - Android
Requirements
After configuring Firebase, add the google-services.json
file to your project/android/app catalog.
Firebase Cloud Messaging
-
Add the google-services dependency to your project’s
build.gradle
file.dependencies { ... classpath 'com.google.gms:google-services:4.3.3' ... }
-
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' ... }
-
Make sure that at the end of the application gradle file, you add plugin: ‘com.google.gms.google-services’
-
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.
- 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); } } }
- To enable banners, handle the intent when the app starts. You can do it in your
MainActivity
by callingRNNotifications.onNotificationReceive
in youronCreate
andonNewIntent
.@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()); }
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, actionIdentifier) {
if (Synerise.Notifications.isSyneriseNotification(payload)) {
Synerise.Notifications.handleNotification(payload, actionIdentifier);
}
},
});
Configuring notification encryption
To enable encrypted push notifications, you must change the configuration of your workspace. See Google Firebase.
In the mobile application, you must set encryption
to true
in the notifications
settings.
Synerise.Initializer()
.withClientApiKey('XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX')
.withBaseUrl(null)
.withDebugModeEnabled(true)
.withCrashHandlingEnabled(true)
.withSettings({
notifications: {
enabled: true,
encryption: true,
},
sdk: {
minTokenRefreshInterval: 5000,
enabled: true,
},
injector: {
automatic: true,
},
})
.init()
The SDK performs the decryption as a part of the Synerise.Notifications.handleNotification
method.
If you use only the Synerise
issuer in push notifications, no more actions are required.
If you need a custom integration of encrypted push notifications, implement the following solution:
Synerise.onReady(function() {
Synerise.Notifications.setListener({
onRegistrationToken: function(token) {
Synerise.Notifications.registerForNotifications(
token,
true,
function() {
console.log('success')
},
function(error) {
console.log(error.message)
}
)
},
onNotification: function(payload, actionIdentifier) {
let isNotificationEncrypted = Synerise.Notifications.isNotificationEncrypted(payload)
var normalizedPayload
if (isNotificationEncrypted) {
normalizedPayload = Synerise.Notifications.decryptNotification(payload)
} else {
normalizedPayload = payload
}
Synerise.Notifications.handleNotification(normalizedPayload, actionIdentifier)
},
})
})
decryptNotification
method returns raw data when the payload is not encrypted. If the crypter fails, the method returns null.