Link Search Menu Expand Document

Snapyr For React Native SDK

The Snapyr React Native SDK makes it simple to connect your web application to the Snapyr platform.

Using the SDK

Step 1: Install the SDK

First, you’ll need to add the SDK to your project using npm. You can install with the following command:

npm install react-native-snapyr-sdk

If you are running your app on iOS, you may need to update pods after install the library:

npx pod-install

Then, re-build and/or re-run the iOS app to include the updated code.

Step 2. Initialize

You’ll need to initialize Snapyr by calling configure() with your SDK write key.

Be sure to do this early in your app’s lifecycle, before calling any other Snapyr functions. If possible, it’s recommended to initialize in your app’s index.js file, even before launching the main app component from App.jsx or App.tsx.

import { configure } from "react-native-snapyr-sdk";

// ...

await configure('YOUR_WRITE_KEY');

You’ll need your app’s Snapyr Write Key. To obtain your write key, please contact Snapyr Customer Service.

Main Snapyr SDK Calls

Identify

This lets you setup information about the current user and tie that individual to all actions taken. You can set traits for a specific user and these traits will be tied to every tracking action taken.

import { identify } from "react-native-snapyr-sdk";

// ...

await identify('userId@here.com', { name: 'Jane Doe', accountBalance: 123.45 });

Snapyr recommends that you make an identify call once when the user first registers or logs in to his / her account, and then call identify again if traits are added – for example if the user links her account to Facebook or email and you now have desired data. Snapyr will merge any old traits with new ones and update any traits that use the same key.

Remember, you can replace the properties and traits in the code samples with variables that represent the data you actually collected.

userId String The database ID of the user. If provided, this optional argument will be sent to destinations as the user ID instead of an anonymous ID
traits Dictionary, optional Contains the traits or properties associated with a userid such as email, address, etc.

Track

The Track call is at the heart of Snapyr and allows you to keep track of events or actions your users perform. Every event can also have associated properties.

import { track } from "react-native-snapyr-sdk";

// ...

await track('purchase', { revenue: 30, currency: 'USD' });

You might also want to track events that indicate key spots hit such as Registered, Logged In, Complete Tutorial, or Purchased an Item.

event String A string that captures the name of the event that is being tracked
properties Dictionary, optional An optional dictionary that tracks the properties of the event

In-App Messaging

The Snapyr SDK makes it easy to handle in-app messages that are triggered by a Snapyr campaign.

Snapyr supports two different types of messages:

  • HTML overlay: if your campaign sends this type of message, the Snapyr SDK will render a window over your application showing the message automatically.
  • Custom: if your campaign sends this type of message, the Snapyr SDK will call a callback that you provide at config time. You can then decide how to use the data in this message - for example, you might update your user’s account balance, or jump to a different screen in your app.

Configuration

To get started, all you need to do is register a callback for in-app messages by calling onSnapyrInAppMessage(...) after initializing Snapyr.

NOTE: In-app messaging requires Snapyr SDK version 1.1.0 or later.

onSnapyrInAppMessage((inappMessage: SnapyrInAppMessage) => {
    console.log("Received Snapyr in-app message!", inappMessage);
    // trigger your own callback code here
});

Fetching/Receiving In-App Messages

When you have in-app messaging enabled, the SDK handles fetching/receiving of in-app messages automatically. There are two ways in which the SDK can receive messages:

  1. Whenever your track or identify events are flushed to the back end, if this triggers any Snapyr campaigns that generate an in-app message for the current user, they will be returned by the back end and trigger in the SDK immediately.
  2. The SDK will also check the back end for any queued-up messages when it first begins, and then start polling the back end for new messages every 30 seconds, or at an interval that you specify in your config.

Acting on a custom InAppMessage

By registering an in-app message callback with onSnapyrInAppMessage(...), you can provide your own code that will be triggered whenever a custom in-app message arrives. The value for this config is a function that receives a SnapyrInAppMessage object as its parameter.

The SnapyrInAppMessage Type

SnapyrInAppMessage has the following definition in TypeScript:

type SnapyrInAppMessage = {
  timestamp: string;
  actionType: SnapyrInAppActionType;
  userId: string;
  actionToken: string;
  content: SnapyrInAppContent;
};
content SnapyrInAppContent The content of the in-app message. This is defined in the Snapyr UI when setting up the campaign that triggered this message, and is generally what you want to check in your callback code. See the next section for more details on SnapyrInAppContent.
timestamp string The datetime when the message was originally sent or scheduled from the back end, in ISO 8601 format.
actionType SnapyrInAppActionType An enum, either SnapyrInAppActionType.Custom (literal string value: 'custom'), for a message that triggers your callback code, or SnapyrInAppActionType.Overlay (literal string value: 'overlay'), for a message that Snapyr automatically displays.
actionToken string A unique token for this message, which is used for tracking KPIs such as impressions for this message.
userId string The user ID that this message was sent to. This should generally be the same as the user ID that your current user is identified with. But in the event that your user has changed accounts, you may want to check that the userId on the message matches your current user ID before acting on the message.

The SnapyrInAppContent Type

SnapyrInAppContent has the following definition in TypeScript:

type SnapyrInAppContent =
  { payloadType: SnapyrInAppPayloadType.JSON; payload: Record<string, any> } |
  { payloadType: SnapyrInAppPayloadType.HTML; payload: string };

Note that type of payload varies depending on the value of payloadType.

payloadType SnapyrInAppPayloadType An enum, either SnapyrInAppPayloadType.JSON (literal string value: 'json') or SnapyrInAppPayloadType.HTML (literal string value: 'html'), as specified on the message and campaign in the Snapyr UI.
payload Record<string, any> | string

The content of the message.

When payloadType is SnapyrInAppPayloadType.JSON, then payload is an object of type Record<string, any> (i.e. a key-value object), containing the parsed JSON content of the message.

When payloadType is SnapyrInAppPayloadType.HTML, then payload is a string, containing the HTML content of the message.

Tracking Analytics for In-App Messages

Snapyr lets you track user interaction metrics for your in-app messages to enable your team to measure the performance of your campaigns.

Automatic tracking with HTML Overlay messages

If you use an HTML overlay message, the Snapyr SDK automatically manages the entire message lifecycle - displaying, closing, and recording metrics. Metrics will be tracked as follows:

  • Impression - this metric is recorded as soon as the HTML overlay is displayed on the user’s screen.
  • Click - this metric is recorded any time a user clicks or taps one of the links or buttons within the overlay. If the click is on a link, the URL will be tracked as an additional piece of data.
  • Dismiss - if the user closes the overlay without clicking on something inside of it first, it’s recorded as a dismiss. If a user clicks a link, then later closes the overlay, it is not tracked as a dismiss.

Manual tracking for custom messages

For custom in-app messages, your code has full control over how, and whether, it displays content to the user. The Snapyr SDK can’t measure analytics automatically for custom code. Instead it provides a set of tracking functions that you can call from your code at the appropriate time. These calls cover the same set of metrics as those of HTML overlay messages.

Every incoming in-app message includes an actionToken parameter, which is a unique string for the message. You’ll need to pass this value back to the tracking calls, which allows Snapyr to automatically connect metrics back to the source message and campaign.

Impression: trackInAppMessageImpression(actionToken: string): Promise<void> Call immediately after you've presented a message to the user.
Click: trackInAppMessageClick(actionToken: string, properties: Record<string, any> = {}): Promise<void> Call when a user clicks on, or otherwise has a positive engagement with, the message. The second parameter, properties, is optional. If you have additional data to record for this click, you can include it here as a key-value object. For example, you might include the url for a link that was clicked.
Dismiss: trackInAppMessageDismiss(actionToken: string): Promise<void> Call if your user dismisses the message without first performing any clicks or other positive engagement.

Push Notification Handling

Push handling for the React Native SDK is still under development. At this time, we require that you use a third party library such as the React Native Push Notifications package to implement base callbacks for getting device tokens and acting on push notification receipt.

Once you have code for receiving a device token, push notification receipt, and push notification interaction, you can use the Snapyr React Native SDK to connect these to Snapyr. This will allow your app to connect to Snapyr campaigns and track metrics for push notifications.

If you are using the React Native Push Notifications package, first follow the package’s setup instructions, as well as the @react-native-community/push-notification-ios setup instructions if you will be building for iOS.

Then, you can follow this sample code in your app’s index.js file to wire up Snapyr push notifications:

// ...

import PushNotificationIOS from "@react-native-community/push-notification-ios";
import PushNotification from "react-native-push-notification";

import { configure, setPushNotificationToken, pushNotificationReceived, pushNotificationTapped } from '@snapyr/react-native-sdk';

const writeKey = "YOUR_WRITE_KEY";
// Configure Snapyr first, then PushNotification. This way we can pass in Snapyr callback methods for
// device token registration and push receipt/tap tracking, ensuring the Snapyr SDK is already initialized
// when they are triggered
configure(writeKey).then(() => {
    PushNotification.configure({
        // Called when Token is generated (iOS and Android)
        onRegister: function (tokenData) {
            setPushNotificationToken(tokenData.token);
        },
        // (required) Called when a remote is received or opened, or local notification is opened
        onNotification: function (notification) {
            if (notification.action) {
                pushNotificationTapped(notification.snapyr);
            } else {
                pushNotificationReceived(notification.snapyr);
            }
            // custom code to handle the incoming notification can go here
    
            // (required) Called when a remote is received or opened, or local notification is opened
            notification.finish(PushNotificationIOS.FetchResult.NoData);
        },
        // (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
        onRegistrationError: function (err) {
            console.error(err.message, err);
        }
    });
});

AppRegistry.registerComponent(appName, () => App);

Then, to ensure that push notifications work fully, complete the following platform-specific steps.

Additional setup: iOS

The following must be completed in Xcode. Navigate to your app’s myRnApp/ios directory and open myRnApp.xcworkspace in Xcode.

Features to enable rich push notification functionality

Snapyr allows marketers to create push notification templates that include rich media and interaction capabilities, such as embedded images in the notification.

In order to enable these capabilities, we need to add a Notification Service Extension to the app.

First, add a new Notification Service Extension target to the project:

  1. Open the project settings. Under the target list, click the + on the bottom to add a new target: Add Target

  2. Find and select Notification Service Extension, and click Next. Notification Service Extension

  3. Enter a name of your choice for the extension, and be sure to select your team in the dropdown. Xcode will automatically append the name you enter to the name of the primary target to produce a matching Bundle Identifier. Click Finish to create the extension. Enter Extension Name

    • NOTE: if Xcode shows a prompt asking if you want to activate the new scheme, you can simply click Cancel.

You now have a Notification Service Extension! Now we need to update the code in NotificationService.swift to handle rich push features.

In the Xcode file navigator, find and open NotificationService.swift under the new extension, and update the code to the following:

import UserNotifications

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        // This method will be called when the notification arrives on the device, before the notification is displayed
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            // Download Snapyr-provided image from URL, if specified
            if let snapyrData = request.content.userInfo["snapyr"] as? Dictionary<String, AnyObject>,
               let urlPath = snapyrData["imageUrl"] as? String,
               let url = URL(string: urlPath) {
                // Notification image must be a url to a local (on-disk) file...
                // Fetch image from network and store in a temp file
                let destination = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(url.lastPathComponent)
                do {
                    let data = try Data(contentsOf: url)
                    try data.write(to: destination)
                    // empty string identifier lets system generate its own unique ID
                    let attachment = try UNNotificationAttachment(identifier: "", url: destination)
                    bestAttemptContent.attachments = [attachment]
                } catch {
                    // On failure, do nothing - notification will continue to process w/o image
                    print("Could not fetch notification image from URL")
                }
            }
            
            contentHandler(bestAttemptContent)
        }
    }
    
    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // In the event that processing rich features takes longer than iOS allows, we'll continue to display the basic notification.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }

}

Additional setup: Android

NOTE: The Snapyr SDK for Android depends on the Firebase Messaging library. If this library isn’t configured correctly, your app may encounter errors at startup.

  1. First, add required dependencies to your app’s build.gradle file, located under myRnApp/android/app/build.gradle.

     ...
    
     // Add `buildscript {}` section at top level, directly before `android {}` section
     buildscript {
         repositories {
             mavenCentral()
             google()
         }
    
         dependencies {
             classpath 'com.google.gms:google-services:4.3.3'
         }
     }
    
     android {
       // existing code generated by React Native
     }
    
     dependencies {
       ...
       // additional dependencies required by Snapyr
       implementation platform('com.google.firebase:firebase-bom:27.1.0')
       implementation 'com.google.firebase:firebase-messaging'
     }
    
     ...
     // Add to the bottom of the file, outside any other section
     apply plugin: 'com.google.gms.google-services'
    
  2. If you have not already done so, add the google-services.json file for your Firebase project to your app’s Android app directory, i.e. myRnApp/android/app/google-services.json.

  3. Add the following to your application’s myRnApp/android/app/src/main/AndroidManifest.xml, as a child of <application>:

     <!-- Used by Snapyr to automatically track notification receipt/interaction -->
     <activity android:name="com.snapyr.sdk.notifications.SnapyrNotificationListener"
         android:exported="false">
         <intent-filter>
             <action android:name="com.snapyr.sdk.notifications.TRACK_BROADCAST" />
             <category android:name="android.intent.category.DEFAULT" />
         </intent-filter>
     </activity>
    
     <!-- Main Snapyr push notification service - renders notifications -->
     <service
         android:name="com.snapyr.sdk.notifications.SnapyrFirebaseMessagingService"
         android:exported="false">
         <intent-filter>
             <action android:name="com.google.firebase.MESSAGING_EVENT" />
         </intent-filter>
     </service>
    
  4. Make sure to add the Network state permission to your application’s AndroidManifest.xml, after the <application> section:

     <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    

That’s it! You should now be able to run your application and start working with Snapyr push notifications.