Integrating Mapp Engage in React Native: Bridge API Guide
    • 5 Minutes to read
    • Dark
      Light

    Integrating Mapp Engage in React Native: Bridge API Guide

    • Dark
      Light

    Article summary

    Overview

    This guide provides step-by-step instructions to integrate Mapp Engage into a React Native app, focusing on initialization, device registration, push notifications, and advanced customization options for Android and iOS platforms. Follow each platform’s specific instructions carefully to ensure smooth integration.

    Procedures

    Step 1: Initializing the Mapp Plugin

    Start by initializing the Mapp plugin in your application to enable its features.

    1. Add Required Files: Include Mapp.js and MappEventEmitter.js in your project.

    2. Initialize Mapp: Call the Mapp.engage() function as the first action in your application to initialize the plugin.

      Mapp.engage(sdkKey: string, googleProjectId: string, server: string, appID: string, tenantID: string);
      • Parameters:

        • sdkKey: Your account’s SDK key.

        • googleProjectId: Optional, for backward compatibility.

        • server: Server for engagement (provided by Mapp).

        • appID and tenantID: Identifiers for your app and Mapp account.

    3. Check if the plugin is ready:

      const ready = await Mapp.isReady();

    Step 2: Platform-Specific Setup

    Complete the following setup based on your target platform.

    For Android

    1. Device registration: Use the following pieces of code to check if the device is registered and retrieve or set device aliases:

      • Device Registration:

        const registered = await Mapp.isDeviceRegistered();
      • Device Alias:

        • Get Alias

          let alias = await Mapp.getAlias();
        • Set Alias

          Mapp.setAlias(”some alias”)
      • Retrieve device information:

        let deviceInfo = await Mapp.getDeviceInfo();
    2. Push Notifications:

      • Check if Push is enabled:

        let enabled = await Mapp.isPushEnabled();
      • Enable or Disable Push Notifications:

        await Mapp.setPushEnabled(false); // Disable
        await Mapp.setPushEnabled(true);  // Enable
      • Request Notification Permission (Android 13+):

        let result = await Mapp.requestPostNotificationPermission();
        if (result) {
          console.log("PERMISSION GRANTED");
        } else {
          console.log("PERMISSION NOT GRANTED");
        }
      • Handle events when a push message is received, opened, or dismissed:

        Mapp.addPushListener((pushMessage) => {
          console.log(JSON.stringify(pushMessage));
          Alert.alert("Push message event", JSON.stringify(pushMessage));
        });

    3. Custom Push Message Setup:

      This is for users handling push messages independently or using an additional push service.

      • To avoid conflicts when using multiple Firebase services, configure custom message handling:

        • Disable the default Mapp service by updating AndroidManifest.xml:

          <service android:name=".MessageService"
                   android:exported="false"
                   tools:node="remove">
              <intent-filter>
                  <action android:name="com.google.firebase.MESSAGING_EVENT" />
              </intent-filter>
          </service>
        • Choose one of the following custom setup options

          • OPTION A - Native Service Implementation

            Create a service extending MessageService to handle push messages.

            public class MyMessageService extends MessageService {
            
                @Override
                public void onCreate() {
                    super.onCreate();
                }
                
                @Override
                public void onMessageReceived(RemoteMessage remoteMessage) {
                    if(remoteMessage.getData().containsKey("p")) {
                        // handle Mapp push messages
                        super.onMessageReceived(remoteMessage);
                    }else{
                        // handle your own push messages
                    }
                }
            
                @Override
                public void onNewToken(String s) {
                    super.onNewToken(s);
            		// subscribe on your own service with firebase token
                }
            }

            Ensure all overridden methods call the super method for plugin compatibility.

          • OPTION B - React Native Implementation Using Firebase Plugins

            • Use React Native’s Firebase plugins to handle push messages:

              • Install the necessary plugins:

                yarn add @react-native-firebase/app
                yarn add @react-native-firebase/messaging
              • After setup, forward Mapp’s push messages to the Mapp plugin:

                import FBMessaging from "@react-native-firebase/messaging";
                
                const handleFirebasePushMessage = async (remoteMessage) => {
                  let isFromMapp = await Mapp.isPushFromMapp(remoteMessage);
                  if (isFromMapp) {
                    Mapp.setRemoteMessage(remoteMessage);
                  }
                };
                
                // Handle push messages based on app state
                FBMessaging().setBackgroundMessageHandler(handleFirebasePushMessage);
                FBMessaging().onMessage(handleFirebasePushMessage);

      Refer to the official Firebase documentation for full setup instructions.

    4. Firebase Device Tokens and Push Messages: To integrate Firebase messaging with Mapp, you need to forward the Firebase device token to the Mapp SDK and manage incoming messages.

      • Forward Firebase Token to Mapp: After obtaining the token from Firebase, send it to Mapp for device registration:

        const token = await FBMessaging().getToken();
        Mapp.setToken(token); // Forward Firebase token to Mapp
      • Check if Push Message is from Mapp: Determine whether a received push message originated from Mapp:

        let isFromMapp = await Mapp.isPushFromMapp(remoteMessage);

        Parameters

        • remoteMessage (RemoteMessage): Message received from Firebase messaging service.

      • Forward Firebase Message to Mapp: Pass any received Firebase messages directly to Mapp:

        Mapp.setRemoteMessage(remoteMessage);

        Parameters:

        • remoteMessage (RemoteMessage): The message from the Firebase messaging service is to be handled by Mapp.

    For iOS

    1. Device Registration: Check if the device is registered and retrieve or set device aliases:

      const registered = await Mapp.isDeviceRegistered();
      let alias = await Mapp.getAlias();
      Mapp.setAlias("your_alias");
    2. Push Notifications:

      • Check if Push is Enabled:

        let enabled = await Mapp.isPushEnabled();
      • Enable or Disable Push Notifications:

        await Mapp.setPushEnabled(true); // Enable
        await Mapp.setPushEnabled(false); // Disable
    3. Push Message Events:

      • Handle events when a push message is received, opened, or dismissed:

        Mapp.addPushListener((pushMessage) => {
          console.log(JSON.stringify(pushMessage));
          Alert.alert("Push message event", JSON.stringify(pushMessage));
        });
      • For rich messages:

        Mapp.addRichMessagesListener((notification) => {
                    console.log(JSON.stringify(notification));
                    Alert.alert(JSON.stringify(notification))
                });

    Step 3: Advanced Features (Both Platforms)

    These features are available on Android and iOS, enabling advanced user engagement, data management, and navigation across platforms.

    In-App Messaging

    Manage and retrieve in-app messages within the application.

    • Fetch Inbox Messages: Retrieve inbox messages for the user.

      Mapp.fetchInboxMessage().then((data) => {
        if (Platform.OS == "ios") {
          Mapp.addInboxMessagesListener((messages) => {
            Alert.alert(JSON.stringify(messages));
          });
        } else {
          Alert.alert(JSON.stringify(data));
        }
      });

      On iOS, inbox messages are received as events and not through a returned promise. Use the didReceiveInboxMessagesHandler event handler to capture them.

    • Fetch Latest Inbox Message: Retrieve the most recent inbox message.

      const latestMessage = await Mapp.fetchLatestInboxMessage();
      if (latestMessage != null) {
        // Use latest message
      }
    • Show In-App Message: Trigger an in-app message based on an event.

      Mapp.triggerInApp("app_open");

      Parameters:

      • event (string): The event-specific trigger (e.g., "app_open").

    • Manage In-App Messages: Mark in-app messages as read, unread, or deleted.

      Mapp.inAppMarkAsRead(templateId: number, eventId: string);
      Mapp.inAppMarkAsUnRead(templateId: number, eventId: string);
      Mapp.inAppMarkAsDeleted(templateId: number, eventId: string);

      Parameters:

      • templateId (number): The template ID of the message.

      • eventId (string): The event ID of the message.

    Geolocation Targeting

    • Start Geofencing

      Mapp.startGeofencing()
          .then((result) => {
              console.log(result);
              Alert.alert("Geofencing start", result);
          });

      Ensure location permissions (COARSE_LOCATION, FINE_LOCATION, BACKGROUND_LOCATION) are requested on Android:

      let result = await Mapp.requestGeofenceLocationPermission();
      if (result) {
        // Start geofencing
      }
    • Stop Geofencing

      Mapp.stopGeofencing()
          .then((result) => {
              console.log(result);
              Alert.alert("Geofencing stop", result);
          });

    Deep Linking

    Handle deep links in push messages to open specific pages in the app:

    Mapp.addDeepLinkingListener((notification) => {
      const uri = new URL(notification.url);
      this.props.navigation.navigate("Home", {
        myLink: uri,
        message_id: notification.action,
      });
    });

    Tags

    Manage channel tags associated with devices.

    • Retrieve Tags:

      Mapp.getTags().then((data) => {
        Alert.alert(JSON.stringify(data));
      });
    • Add a Tag: Assign a new tag to the device.

      Mapp.addTag("tagName");

      Parameters:

      • tag (string): The tag name to be assigned to the device.

    • Remove a Tag: Remove a tag from the device.

      Mapp.removeTag("tagName");

      Parameters:

      • tag (string): The tag name to be removed.

    Custom Fields

    Set custom attribute values for specific fields in the Mapp system.

    • Set String Field: Assign a string value to a specified key.

      Mapp.setAttributeString("some key", "some value");

      Parameters:

      • key (string): The field key.

      • value (string): The string value associated with the key.

    • Set Numeric Field: Assign a numeric value to a specified key.

      Mapp.setAttributeInt("some key", 34);

      Parameters:

      • key (string): The field key.

      • value (number): The numeric value (e.g., 34, 34.54).

    • Set Boolean Field (Android only): Assign a boolean value to a specified key.

      Mapp.setAttributeBoolean("some key", true);

      Parameters:

      • key (string): The field key.

      • value (boolean): The boolean value (true or false).

    Logout

    To log out and disable push notifications:

    Mapp.logOut(pushEnabled);
    • Parameters:

      • pushEnabled (boolean): Determines whether push notifications remain enabled after logging out.




    Was this article helpful?


    What's Next
    ESC

    AI Assistant, facilitating knowledge discovery through conversational intelligence