npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2019 – Ryan Hefner

react-native-branch

v3.1.1

Published

Branch Metrics React Native SDK

Downloads

310,452

Readme

Branch Metrics React Native SDK Reference

Travis npm version npm downloads MIT licensed

This is a repository of our open source React Native SDK. The information presented here serves as a reference manual for the SDK. See the table of contents below for a complete list of the content featured in this document.


React Native Reference

  1. External resources
  1. Getting started
  1. Branch general methods
  1. Branch Universal Objects
  1. Referral rewards methods
  1. General support

Installation

Note that the react-native-branch module requires react-native >= 0.40.

  1. yarn add react-native-branch
  2. (Optional) Add a branch.json file to the root of your app project. See https://rnbranch.app.link/branch-json.
  3. react-native link react-native-branch
  4. Install the native Branch SDK using CocoaPods or Carthage.
  5. Follow the setup instructions.

Note: This SDK currently does not work in projects using NPM instead of yarn. See #433. The RN toolchain will use yarn by default. Please use yarn add react-native-branch to add the SDK to your project.


Updating from an earlier version or starting with v3.0.0

The native SDKs are no longer bundled into this module. The native Android SDK will be installed from Maven via Gradle. You must add the native Branch iOS SDK to your project either using CocoaPods or Carthage.

To fix a longstanding build issue with Android, it is necessary to take the native Branch Android SDK from Maven rather than from the react-native-branch module, starting with version 3.0.0. This now happens transparently via Gradle. If you previously added implementation fileTree(dir: 'libs', include: ['*.jar']) to your app/build.gradle only for React Native Branch, you may remove it, unless it is now used by other code.

Remove any direct reference to io.branch.sdk.android:library in your dependencies, e.g. io.branch.sdk.android:library:3.1.1. This has the potential to cause conflicts. This module imports the Branch SDK directly.

The result in your app/build.gradle should be something like

dependencies {
    implementation project(':react-native-branch')
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

If you're using an older version of Gradle, you may need compile instead of implementation.

It is recommended to replace Branch.getAutoInstance in your Application.onCreate method with RNBranchModule.getAutoInstance. This is required in order to set Branch keys in the branch.json file.

@Override
public void onCreate() {
  super.onCreate();
  SoLoader.init(this, /* native exopackage */ false);
  // Replace Branch.getAutoInstance(this); with:
  RNBranchModule.getAutoInstance(this);
}

If you are not already using the React pod to build your app, it will be necessary to convert your Xcode project.

The cached_initial_event key in the params returned in the subscribe callback has been renamed to +rn_cached_initial_event.


Register Your App

You can sign up for your own app id at https://dashboard.branch.io.


Setup

iOS Setup

Modify your AppDelegate as follows:

Objective-C

In AppDelegate.m

Note that if you are not using the React pod, or if you don't have use_frameworks! in your Podfile, and your AppDelegate is written in Objective-C, you should replace @import react_native_branch; with #import <react-native-branch/RNBranch.h>. Also note that CocoaPods 1.7.0 breaks iOS builds using the react-native-branch pod. Please update to version 1.7.1 instead. See #461.

@import react_native_branch; // at the top

// Use this instead if are not using the React pod or you don't use_frameworks! in your Podfile.
// #import <react-native-branch/RNBranch.h>

// Initialize the Branch Session at the top of existing application:didFinishLaunchingWithOptions:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Uncomment this line to use the test key instead of the live one.
    // [RNBranch useTestInstance]
    [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES]; // <-- add this

    NSURL *jsCodeLocation;
    //...
}

// Add the openURL and continueUserActivity functions
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    if (![RNBranch.branch application:app openURL:url options:options]) {
        // do other deep link routing for the Facebook SDK, Pinterest SDK, etc
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *restorableObjects))restorationHandler {
    return [RNBranch continueUserActivity:userActivity];
}

Note: Some applications may be using the deprecated application:openURL:sourceApplication:annotiation: instead of application:openURL:options:.

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    if (![RNBranch.branch application:application openURL:url sourceApplication:sourceApplication annotation:annotation]) {
        // do other deep link routing for the Facebook SDK, Pinterest SDK, etc
    }
    return YES;
}

If you do not yet have either method in your app, prefer the first (application:openURL:options:), which will be supplied by autocompletion in Xcode.

Swift

If you're using Swift in your iOS native code, it is recommended that you include use_frameworks! in your Podfile. This is necessary to use any pods written in Swift.

If you are using Swift without use_frameworks! in your Podfile, you will require a bridging header in order to use any React Native plugin in Swift.

Add #import <react-native-branch/RNBranch.h> to your Bridging header if you have one.

If you have use_frameworks! in your Podfile, you may simply use a Swift import.

In AppDelegate.swift:

import react_native_branch // omit if using a bridging header

// Initialize the Branch Session at the top of existing application:didFinishLaunchingWithOptions:
func application(_ application: UIApplication, didFinishLaunchingWithOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Uncomment this line to use the test key instead of the live one.
    // RNBranch.useTestInstance()
    RNBranch.initSession(launchOptions: launchOptions, isReferrable: true) // <-- add this

    //...
}

// Add the openURL and continueUserActivity functions
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    return RNBranch.branch.application(app, open: url, options: options)
}

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
    return RNBranch.continue(userActivity)
}

These instructions are for Swift 3 and 4.

iOS Project Configuration

After modifying your AppDelegate:

  1. Add a Dictionary or String entry branch_key with your Branch key to your info.plist

  2. Configure for Universal Linking

  3. If using a custom domain in the Branch Dashboard or one or more non-Branch domains, add the branch_universal_link_domains key to your Info.plist.


Android Setup

Gradle dependency

If you use react-native link, no further change is necessary to your app/build.gradle.

In a native app, import the react-native-branch project like this:

implementation project(':react-native-branch')

If you're using an older version of Gradle, you may need compile rather than implementation. If you are already using the native Branch SDK in your app, it will now be imported from Maven via react-native-branch as a dependency. Remove any reference to io.branch.sdk.android:library from your dependencies to avoid conflicts.

Also add the project to your settings.gradle:

include ':react-native-branch'
project(':react-native-branch').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-branch/android')

The location of your node_modules folder may vary.

Application code

Add RNBranchPackage to packages list in getPackages() MainApplication.java (android/app/src/[...]/MainApplication.java). Note that this is automatically done if you used react-native link.

Also add a call to RNBranchModule.getAutoinstance() in onCreate() in the same source file. This has to be done even if you used react-native link.

// ...

// import Branch and RNBranch
import io.branch.rnbranch.RNBranchPackage;
import io.branch.rnbranch.RNBranchModule;

//...

    // add RNBranchPackage to react-native package list
    @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
                new MainReactPackage(),
                new RNBranchPackage(), // <-- add this

    // ...

    // add onCreate() override
    @Override
    public void onCreate() {
      super.onCreate();
      RNBranchModule.getAutoInstance(this);
    }

Override onStart and onNewIntent in MainActivity.java to handle Branch links (android/app/src/[...]/MainActivity.java). This has to be done regardless whether you used react-native link.

import io.branch.rnbranch.*; // <-- add this
import android.content.Intent; // <-- and this

public class MainActivity extends ReactActivity {

    @Override
    protected String getMainComponentName() {
        return "base";
    }

    // Override onStart, onNewIntent:
    @Override
    protected void onStart() {
        super.onStart();
        RNBranchModule.initSession(getIntent().getData(), this);
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }
    // ...
}

Android Project Configuration

  1. Configure AndroidManifest.xml. Be sure to set android:launchMode="singleTask" on your main activity.

  2. Register for Google Play Install Referrer. The "receiver" element needs to be added to the "application" node in AndroidManifest.xml

  3. Register a URI scheme

  • The "intent-filter" element needs to be added to the activity node, whose android:name is "com.yourAppName.MainActivity". This node is in the "application" node.
  • If you already have an intent-filter tag, this has to be added as an additional one.
  • Make sure to replace "yourApp" with the scheme you specified in the Branch dashboard.
  1. Enable Auto Session Management. Simply add the "android:name" attribute to your "application" node in your AndroidManifest.xml

  2. Enable App Links for Android M and above (optional but recommended)

  3. Add your Branch key to AndroidManifest: Inside of application node add <meta-data android:name="io.branch.sdk.BranchKey" android:value="your_branch_key" />

  4. Add the following to your android/app/proguard-rules.pro file:

-dontwarn io.branch.**

Please see the Branch SDK Integration Guide for complete setup instructions.


Example apps

There are six example apps in this repo, including a tutorial app. See the examples subdirectory for more details.


SDK Documentation

Register a subscriber

To be called back when a link is opened, register a subscriber callback function using the branch.subscribe method. Note that unlike the underlying native SDKs, you do not have to initialize the Branch session from JavaScript. This is done in native code at app launch, before the JavaScript initializes. If the app was opened from a link, the initial link is cached by the native layer and returned to the JavaScript subscriber afterward. This method may be called repeatedly in different app components. To route links in a pure React Native app, call this method in componentDidMount in a component that is mounted at app launch.

In a native app that includes a React Native component, link routing will usually be done at the native level. This method may still be called from JavaScript for purposes other than link routing (e.g. custom analytics). Other Branch SDK methods may be called in this case without calling branch.subscribe at all in JavaScript.

The callback function you supply to the branch.subscribe method is called whenever a link is opened and at certain other times, such as successful SDK initialization without a deferred deep link.

Method

branch.subscribe(listener)
Parameters

listener: A function taking an object argument with the shape { error, params }. The error argument is a string. The params argument is an object. See Params object for details on the contents.

Return

The return value of branch.subscribe is a function that cancels the subscription when called.

Example

import branch from 'react-native-branch'

branch.subscribe(({ error, params }) => {
  if (error) {
    console.error('Error from Branch: ' + error)
    return
  }

  // params will never be null if error is null

  if (params['+non_branch_link']) {
    const nonBranchUrl = params['+non_branch_link']
    // Route non-Branch URL if appropriate.
    return
  }

  if (!params['+clicked_branch_link']) {
    // Indicates initialization success and some other conditions.
    // No link was opened.
    return
  }

  // A Branch link was opened.
  // Route link based on data in params.
})

Unregister a subscriber

The return value of branch.subscribe is a function that cancels the subscription when called. Call this in componentWillUnmount.

Example

import branch from 'react-native-branch'

class MyApp extends Component {
  _unsubscribeFromBranch = null

  componentDidMount() {
    _unsubscribeFromBranch = branch.subscribe({ error, params } => {
      // ...
    })
  }

  componentWillUnmount() {
    if (_unsubscribeFromBranch) {
      _unsubscribeFromBranch()
      _unsubscribeFromBranch = null
    }
  }
}

Skip cached initial launch event

Any initial link cached by the native layer will be returned to the callback supplied to branch.subscribe immediately if the JavaScript method is called for the first time after app launch. In case, app does not need to receive the cached initial app launch link event, call branch.skipCachedEvents() before branch.subscribe to skip returning it.

Method

branch.skipCachedEvents()

Also, if a cached initial app launch link event is returned, params will contain a key +rn_cached_initial_event, set to true.

Example

import branch from 'react-native-branch'

branch.skipCachedEvents()
branch.subscribe({ error, params } => {
  // ...
})
import branch from 'react-native-branch'

branch.subscribe({ error, params } => {
  if ('+rn_cached_initial_event' in params) {
    // ...
  }
})

Retrieve session (install or open) params

These session parameters will be available at any point later on with this command. If no parameters are available then Branch will return an empty dictionary. This refreshes with every new session (app installs AND app opens).

Method

branch.getLatestReferringParams(synchronous = false)
Return

A promise. On resolution, the promise returns an object containing the parameters from the latest link open or install. See Params object for details on the contents. Depending on the value of the argument, the promise may return right away, possibly with values from the user defaults (iOS) or user preferences (Android) or wait until an open response is received.

Example

import branch from 'react-native-branch'

// don't wait for open response
const latestParams = await branch.getLatestReferringParams()

// wait for open response
const latestParams = await branch.getLatestReferringParams(true)

Retrieve Install (Install Only) Parameters

If you ever want to access the original session params (the parameters passed in for the first install event only), you can use this line. This is useful if you only want to reward users who newly installed the app from a referral link. Note that these parameters can be updated when setIdentity: is called and identity merging occurs.

Method

branch.getFirstReferringParams()
Return

A promise. On resolution, the promise returns an object containing the referring parameters from the initial app installation. See Params object for details on the contents.

Example

import branch from 'react-native-branch'

const latestParams = await branch.getFirstReferringParams()

Persistent Identities

Often, you might have your own user IDs, or want referral and event data to persist across platforms or uninstall/reinstall. It's helpful if you know your users access your service from different devices. This where we introduce the concept of an 'identity'.

Method

branch.setIdentity(userIdentity)
Parameters

userIdentity: A string specifying the user identity to use.

Example

import branch from 'react-native-branch'

branch.setIdentity('theUserId')

Logout

If you provide a logout function in your app, be sure to clear the user when the logout completes. This will ensure that all the stored parameters get cleared and all events are properly attributed to the right identity.

Warning: This call will clear the promo credits and attribution on the device.

Method

branch.logout()

Example

import branch from 'react-native-branch'

branch.logout()

Programmatic deep linking

The Branch SDK automatically triggers the branch.subscribe callback whenever a link is received in the app via App Links, Universal Links or custom URI schemes. There may be other cases where you want to trigger a link open programmatically, e.g. from a push notification or a QR reader. Use the branch.openURL method to trigger an open of a Branch link from anywhere in your app. In the case of native apps integrating an RN component, this will also trigger the native deep link handler callback.

Note: This method does nothing if passed a link that is not recognized by the SDK. Non-Branch links may be passed for any domain that is configured for the app. This method does not pass the URL to the operating system or a browser.

Android note: If not using the newActivity option, it is necessary to move the call to the RNBranch.initSession method to the main activity's onResume method instead of onStart:

@Override
protected void onResume() {
  super.onResume();
  RNBranch.initSession(getIntent().getData(), this);
}

Method

branch.openURL(url, options)
Parameters

url: A String containing a Branch link
options: (Optional) An object with keys to supply option values (see below)

Options

newActivity: (Android) Finish the current activity before opening the link. Results in a new activity window. Ignored on iOS.

Example

import branch from 'react-native-branch'

branch.openURL("https://myapp.app.link/xyz")
branch.openURL("https://myapp.app.link/xyz", {newActivity: true})

Tracking User Actions and Events

Use the BranchEvent interface to track special user actions or application specific events beyond app installs, opens, and sharing. You can track events such as when a user adds an item to an on-line shopping cart, or searches for a keyword, among others.

The BranchEvent interface provides an interface to add contents represented by BranchUniversalObject in order to associate app contents with events.

Analytics about your app's BranchEvents can be found on the Branch dashboard, and BranchEvents also provide tight integration with many third party analytics providers.

Note: The BranchEvent class supersedes the userCompletedAction method on the Branch Universal Object and the branch.sendCommerceEvent method, both of which should be considered deprecated.

Constructor

new BranchEvent(name, contentItems = null, params = {})

Parameters

name: String indicating the name of the event to log. Pass a standard event constant, such as BranchEvent.ViewItem or a custom event name.
contentItems: Zero or more Branch Universal Objects associated with this event. Pass null, a single Branch Universal Object or an array of them.
params: Optional Object with properties to be set on the BranchEvent (see below).

Properties

The following properties may be passed as arguments to the constructor or set directly on the object after construction.

name: A string indicating the name of the event, as passed to the constructor. May be set after construction.
contentItems: An array of Branch Universal Objects associated with this event. May be empty. Contents may be adjusted after construction.

The following properties may be passed to the constructor in the params or set directly on the object after construction.

transactionID: String indicating a transaction ID
currency: An ISO currency code (e.g. USD, JPY, EUR)
revenue: Revenue associated with this event as a string or number
shipping: Shipping cost associated with this event as a string or number
tax: Tax associated with this event as a string or number
coupon: String indicating a coupon code for this event
affiliation: String indicating an affiliation for this event
description: String indicating a description for this event
searchQuery: String indicating a search query for this event
customData: Object containing arbitrary key-value pairs for this event. Values must be strings.

logEvent method

branchEvent.logEvent()

Logs a BranchEvent with all associated parameters.

Examples

Log a view on a single Branch Universal Object.

new BranchEvent(BranchEvent.ViewItem, buo).logEvent()

Log a view on a multiple Branch Universal Objects.

new BranchEvent(BranchEvent.ViewItems, [buo1, buo2]).logEvent()

Log a Purchase event on a Branch Universal Object.

new BranchEvent(BranchEvent.Purchase, buo, {
  revenue: 20,
  shipping: 2,
  tax: 1.6,
  currency: 'USD'}).logEvent()

Log a Search event.

let event = new BranchEvent(BranchEvent.Search)
event.searchQuery = "tennis rackets"
event.logEvent()

Log a custom event.

new BranchEvent("UserScannedItem", buo).logEvent()

When logging an event on a single Branch Universal Object, the logEvent method may be called on the Branch Universal Object.

buo.logEvent(BranchEvent.Purchase, { revenue: 20 })

This is equivalent to

new BranchEvent(BranchEvent.Purchase, buo, { revenue: 20 }).logEvent()

Standard events

Event constantDescription
BranchEvent.AddToCartStandard Add to Cart event
BranchEvent.AddToWishlistStandard Add to Wishlist event
BranchEvent.ViewCartStandard View Cart event
BranchEvent.InitiatePurchaseStandard Initiate Purchase event
BranchEvent.AddPaymentInfoStandard Add Payment Info event
BranchEvent.PurchaseStandard Purchase event
BranchEvent.SpendCreditsStandard Spend Credits event
BranchEvent.SearchStandard Search event
BranchEvent.ViewItemStandard View Item event for a single Branch Universal Object
BranchEvent.ViewItemsStandard View Items event for multiple Branch Universal Objects
BranchEvent.RateStandard Rate event
BranchEvent.ShareStandard Share event
BranchEvent.CompleteRegistrationStandard Complete Registration event
BranchEvent.CompleteTutorialStandard Complete Tutorial event
BranchEvent.AchieveLevelStandard Achieve Level event
BranchEvent.AchievementUnlockedStandard Unlock Achievement event

Debug mode and Apple Search Ads attribution

Certain methods in the native SDKs cannot be easily exposed to JavaScript, because they must be called before the native SDKs initialize, which happens well before JavaScript finishes loading. To use these methods, two options are available.


Enable or Disable User Tracking

In order to comply with tracking requirements, you can disable tracking at the SDK level. Simply call:

branch.disableTracking(true)

This will prevent any Branch requests from being sent across the network, except for the case of deep linking. If someone clicks a Branch link, but has expressed not to be tracked, we will return deep linking data back to the client but without tracking information captured.

In do-not-track mode, you will still be able to create and share links. They will not have identifiable information. Event tracking won’t pass data back to the server if a user has expressed to not be tracked. You can change this behavior at any time, but calling the above function. This information will be saved and persisted.


Referral System Rewarding Functionality

Get Reward Balance

Reward balances change randomly on the backend when certain actions are taken (defined by your rules), so you will need to make an asynchronous call to retrieve the balance.

Method

branch.loadRewards(bucket)
Parameters

bucket: (Optional) The bucket to get the credit balance for

Return

Example

import branch from 'react-native-branch'

let rewards = await branch.loadRewards(bucket)

Redeem All or Some of the Reward Balance (Store State)

Redeeming credits allows users to cash in the credits they've earned. Upon successful redemption, the user's balance will be updated reflecting the deduction.

Method

branch.redeemRewards(amount, bucket)
Parameters

amount: The amount to redeem
bucket: (Optional) The bucket to redeem from

Example

import branch from 'react-native-branch'

let redeemResult = await branch.redeemRewards(amount, bucket)

Get Credit History

This call will retrieve the entire history of credits and redemptions from the individual user.

Method

branch.getCreditHistory()
Return

A promise. On resolution, the promise returns an array containing the current user's credit history.

Example

let creditHistory = await branch.getCreditHistory()

Branch Universal Object (for deep links, content analytics and indexing)

The Branch Universal Object represents an item of content in your app, e.g. an article, a video, a user profile or a post.

Branch Universal Object best practices

Here are a set of best practices to ensure that your analytics are correct, and your content is ranking on Spotlight effectively.

  1. Set the canonicalIdentifier to a unique, de-duped value across instances of the app.
  2. Ensure that the title, contentDescription and contentImageUrl properly represent the object.
  3. Initialize the Branch Universal Object and call logEvent(BranchEvent.ViewItem) on page load (in componentDidMount).
  4. Call showShareSheet and generateShortLink later in the life cycle, when the user takes an action that needs a link.
  5. Call the additional object events (purchase, share completed, etc) when the corresponding user action is taken.

Practices to avoid: 1. Don't set the same title, contentDescription and contentImageUrl across all objects. 2. Don't wait to initialize the object and register views until the user goes to share. 3. Don't wait to initialize the object until you conveniently need a link. 4. Don't create many objects at once and register views in a loop.


Create Branch Universal Object

To create a Branch Universal Object, use the branch.createBranchUniversalObject method. Note that unlike the underlying SDKs, all parameters to the Branch Universal Object must be supplied at creation. These parameters are not represented as properties on the JavaScript object returned by this method. They are stored on the underlying native Branch Universal Object.

Method

branch.createBranchUniversalObject(canonicalIdentifier, properties)
Parameters

canonicalIdentifier: A string that uniquely identifies this item of content
properties: An object containing properties defining the Branch Universal Object. See Branch Universal Object Properties for a list of available properties.

Return

A promise. On resolution, the promise returns an object with a number of methods, documented below.

Example

import branch from 'react-native-branch'

let branchUniversalObject = await branch.createBranchUniversalObject('canonicalIdentifier', {
  locallyIndex: true,
  title: 'Cool Content!',
  contentDescription: 'Cool Content Description'}),
  contentMetadata: {
    ratingAverage: 4.2,
    ratingCount: 100,
    ratingMax: 5.0,
    customMetadata: {
      prop1: 'test',
      prop2: 'abc'
    }
  }
})

Register user actions on an object

The logEvent method on the Branch Universal Object is a convenient shortcut for logging a BranchEvent on a single Branch Universal Object. See Tracking user actions and events for more details on BranchEvent.

Method

branchUniversalObject.logEvent(name, params = {})

Parameters

name: A string indicating the name of the event. May be a standard event defined on BranchEvent or a custom event name.
params: An optional Object containing parameters for the BranchEvent

Examples

branchUniversalObject.logEvent(BranchEvent.ViewItem)
branchUniversalObject.logEvent(BranchEvent.Purchase, {
  revenue: 20,
  shipping: 2,
  tax: 1.6,
  currency: 'USD'
})

List content on Spotlight

To list content on Spotlight, set the locallyIndex property to true and log a BranchEvent.ViewItem or BranchEvent.ViewItems event.

Note: Listing on Spotlight requires adding CoreSpotlight.framework to your Xcode project.

Note that the automaticallyListOnSpotlight property and the listOnSpotlight() method are deprecated in favor of this mechanism.

Example

import branch, { RegisterViewEvent } from 'react-native-branch'

let branchUniversalObject = await branch.createBranchUniversalObject('canonicalIdentifier', {
  locallyIndex: true,
  // other properties
})

branchUniversalObject.logEvent(BranchEvent.ViewItem)

Shortened Links

Once you've created your Branch Universal Object, which is the reference to the content you're interested in, you can then get a link back to it with the mechanisms described below.

Method

branchUniversalObject.generateShortUrl(linkProperties, controlParams)
Parameters

linkProperties: An object containing properties to define the link. See Link Properties Parameters for available properties.
controlParams: (Optional) An object containing control parameters to override redirects specified in the Branch Dashboard. See Control Parameters for a list of available parameters.

Return

A promise. On resolution, the promise returns an object with the shape { url }. The url property is a string containing the generated short URL.

Example

import branch from `react-native-branch`

let branchUniversalObject = await branch.createBranchUniversalObject(...)

let linkProperties = { feature: 'share', channel: 'RNApp' }
let controlParams = { $desktop_url: 'http://example.com/home', $ios_url: 'http://example.com/ios' }

let {url} = await branchUniversalObject.generateShortUrl(linkProperties, controlParams)

Share sheet

Once you've created your Branch Universal Object, which is the reference to the content you're interested in, you can then automatically share it without having to create a link using the mechanism below.

The Branch SDK includes a wrapper around the system share sheet that will generate a Branch short URL and automatically tag it with the channel the user selects (Facebook, Twitter, etc.). Note that certain channels restrict access to certain fields. For example, Facebook prohibits you from pre-populating a message.

Method

branchUniversalObject.showShareSheet(shareOptions, linkProperties, controlParams)
Parameters

*shareOptions: An object containing any of the following properties:

KEYTYPEMEANING
messageHeaderstringThe header text
messageBodystringThe body text
emailSubjectstringThe subject of the email channel if selected

linkProperties: An object containing properties to define the link. See Link Properties Parameters for available properties.
controlParams: (Optional) An object containing control parameters to override redirects specified in the Branch Dashboard. See Control Parameters for a list of available parameters.

Return

A promise. On resolution, the promise returns an object with the shape { channel, completed, error }. The completed property is a boolean specifying whether the operation was completed by the user. The channel property is a string specifying the share channel selected by the user. The error property is a string. If non-null, it specifies any error that occurred.

Example

import branch from `react-native-branch`

let branchUniversalObject = await branch.createBranchUniversalObject(...)

let linkProperties = { feature: 'share', channel: 'RNApp' }
let controlParams = { $desktop_url: 'http://example.com/home', $ios_url: 'http://example.com/ios' }

let shareOptions = { messageHeader: 'Check this out', messageBody: 'No really, check this out!' }

let {channel, completed, error} = await branchUniversalObject.showShareSheet(shareOptions, linkProperties, controlParams)

Releasing native resources

The Branch Universal Object is a construct in the underlying native SDK that is exposed using a JavaScript object that is returned by the createBranchUniversalObject method. For best performance, call the release() method on the Branch UniversalObject when the Branch Universal Object is no longer in use. Native resources will eventually be reclaimed without calling this method. Calling it ensures that the resources are reclaimed promptly.

Method

branchUniversalObject.release()

Example

import branch, { BranchEvent } from `react-native-branch`

class CustomComponent extends Component {
  buo = null

  componentDidMount() {
    this.buo = await branch.createBranchUniversalObject(...)
    this.buo.logeEvent(BranchEvent.ViewItem)
  }

  componentWillUnmount() {
    if (this.buo) {
      this.buo.release()
      this.buo = null
    }
  }
}

Branch Universal Object Properties

KeyTYPEDESCRIPTION
automaticallyListOnSpotlight (deprecated)BoolList this item on Spotlight (iOS). Ignored on Android. Deprecated. Please use locallyIndex instead.
canonicalIdentifierStringThe object identifier
contentDescriptionStringObject Description
contentImageUrlStringThe Image URL
contentIndexingMode (deprecated)StringIndexing Mode 'private' or 'public' Deprecated. Please use locallyIndex and publiclyIndex instead.
contentMetadataObjectSee Branch Universal Object Content Metadata
currency (deprecated)StringA 3-letter ISO currency code (used with price) Deprecated. Please use contentMetadata.currency instead.
expirationDateStringA UTC expiration date, e.g. 2018-02-01T00:00:00
keywordsArrayAn array of keyword strings
locallyIndexBoolList this item on Spotlight (iOS). No current Android implementation.
metadata (deprecated)ObjectCustom key/value. Deprecated. Please use contentMetadata.customMetadata instead.
price (deprecated)FloatA floating-point price (used with currency) Deprecated. Please use contentMetadata.price instead.
publiclyIndexBoolList in a public search index.
titleStringThe object title
type (deprecated)StringMIME type for this content Deprecated. Please use contentMetadata.contentSchema instead.

Branch Universal Object Content Metadata

KeyTYPEDESCRIPTION
contentSchemaStringSee Content Schema
quantityNumberItem quantity
priceString/NumberUsed with currency
currencyStringAn ISO currency code. Must also specify price.
skuStringProduct SKU
productNameStringProduct name
productBrandStringProduct brand
productCategoryStringSee Product Category
productVariantStringProduct variant
conditionStringSee Condition
ratingAverageNumberAverage rating
ratingCountNumberRating count
ratingMaxNumberMaximum rating
addressStreetStringAddress street
addressCityStringAddress city
addressRegionStringAddress region
addressCountryStringAddress country
addressPostalCodeStringAddress postal code
latitudeNumberLocation latitude
longitudeNumberLocation longitude
imageCaptionsArrayArray of strings
customMetadataObjectValues must be strings

Content Schema

Allowed string values for Branch Universal Object contentSchema property.

Value
'COMMERCE_AUCTION'
'COMMERCE_BUSINESS'
'COMMERCE_OTHER'
'COMMERCE_PRODUCT'
'COMMERCE_RESTAURANT'
'COMMERCE_SERVICE'
'COMMERCE_TRAVEL_FLIGHT'
'COMMERCE_TRAVEL_HOTEL'
'COMMERCE_TRAVEL_OTHER'
'GAME_STATE'
'MEDIA_IMAGE'
'MEDIA_MIXED'
'MEDIA_MUSIC'
'MEDIA_OTHER'
'MEDIA_VIDEO'
'OTHER'
'TEXT_ARTICLE'
'TEXT_BLOG'
'TEXT_OTHER'
'TEXT_RECIPE'
'TEXT_REVIEW'
'TEXT_SEARCH_RESULTS'
'TEXT_STORY'
'TEXT_TECHNICAL_DOC'

Condition

Allowed string values for Branch Universal Object condition property.

Value
'OTHER'
'EXCELLENT'
'NEW'
'GOOD'
'FAIR'
'POOR'
'USED'
'REFURBISHED'

Product Category

Allowed string values for Branch Universal Object productCategory property.

Value
'Animals & Pet Supplies'
'Apparel & Accessories'
'Arts & Entertainment'
'Baby & Toddler'
'Business & Industrial'
'Cameras & Optics'
'Electronics'
'Food, Beverages & Tobacco'
'Furniture'
'Hardware'
'Health & Beauty'
'Home & Garden'
'Luggage & Bags'
'Mature'
'Media'
'Office Supplies'
'Religious & Ceremonial'
'Software'
'Sporting Goods'
'Toys & Games'
'Vehicles & Parts'

Link Properties Parameters

KEYTYPEMEANING
aliasstringSpecify a link alias in place of the standard encoded short URL (e.g., [branchsubdomain]/youralias or yourdomain.co/youralias). Link aliases are unique, immutable objects that cannot be deleted. Aliases on the legacy bnc.lt domain are incompatible with Universal Links and Spotlight
campaignstringUse this field to organize the links by actual campaign. For example, if you launched a new feature or product and want to run a campaign around that
channelstringUse channel to tag the route that your link reaches users. For example, tag links with ‘Facebook’ or ‘LinkedIn’ to help track clicks and installs through those paths separately
featurestringThis is the feature of your app that the link might be associated with. eg: if you had built a referral program, you would label links with the feature referral
stagestringUse this to categorize the progress or category of a user when the link was generated. For example, if you had an invite system accessible on level 1, level 3 and 5, you could differentiate links generated at each level with this parameter
tagsarrayThis is a free form entry with unlimited values. Use it to organize your link data with labels that don’t fit within the bounds of the above

Control parameters

Specify control parameters in calls to generateShortUrl and showShareSheet.

All Branch control parameters are supported. See here for a complete list. In particular, these control parameters determine where the link redirects.

KEYTYPEMEANING
$fallback_urlstringChange the redirect endpoint for all platforms - so you don’t have to enable it by platform
$desktop_urlstringChange the redirect endpoint on desktops
$android_urlstringChange the redirect endpoint for Android
$ios_urlstringChange the redirect endpoint for iOS
$ipad_urlstringChange the redirect endpoint for iPads
$fire_urlstringChange the redirect endpoint for Amazon Fire OS
$blackberry_urlstringChange the redirect endpoint for Blackberry OS
$windows_phone_urlstringChange the redirect endpoint for Windows OS

Params object

The params object is returned by various linking methods including subscribe, getLatestReferringParams, and getFirstReferringParams. Params will contain any data associated with the Branch link that was clicked before the app session began.

Branch returns explicit parameters every time. Here is a list, and a description of what each represents.

  • ~ denotes analytics
  • + denotes information added by Branch
ParameterMeaning
~channelThe channel on which the link was shared, specified at link creation time
~featureThe feature, such as invite or share, specified at link creation time
~tagsAny tags, specified at link creation time
~campaignThe campaign the link is associated with, specified at link creation time
~stageThe stage, specified at link creation time
~creation_sourceWhere the link was created ('API', 'Dashboard', 'SDK', 'iOS SDK', 'Android SDK', or 'Web SDK')
~referring_linkThe referring link that drove the install/open, if present
~idAutomatically generated 18 digit ID number for the link that drove the install/open, if present
+match_guaranteedTrue or false as to whether the match was made with 100% accuracy
+referrerThe referrer for the link click, if a link was clicked
+phone_numberThe phone number of the user, if the user texted himself/herself the app
+is_first_sessionDenotes whether this is the first session (install) or any other session (open)
+clicked_branch_linkDenotes whether or not the user clicked a Branch link that triggered this session
+click_timestampEpoch timestamp of when the click occurred
+urlThe full URL of the link that drove the install/open, if present (e.g. bnc.lt/m/abcde12345)

See also Deep Link Routing on the Branch documentation site for more information.

Any additional data attached to the Branch link will be available unprefixed.


Troubleshooting

Example apps for testing

See the examples folder for a number of example apps that demonstrate usage of the SDK and can be used for testing. There is also a tutorial app that walks you through integrating the Branch SDK step by step.

Simulate an install

Do not test in production.

This requires a native method call that must be made before JS has loaded. There are two options.

  1. Use a branch.json file with your project. See https://rnbranch.app.link/branch-json for full details. Add "debugMode": true to branch.debug.json:

    {
      "appleSearchAdsDebugMode": true,
      "debugMode": true,
      "delayInitToCheckForSearchAds": true
    }

    Do not add this setting to branch.json, or it will be enabled for release builds.

  2. Modify your native app code.

    Android

    Simulated installs may be enabled on Android by adding <meta-data android:name="io.branch.sdk.TestMode" android:value="true"/> to the application element of your Android manifest. Use this in a build type such as debug or a product flavor, or be sure to remove it from your manifest before releasing to prod. See https://docs.branch.io/pages/apps/android/#simulate-an-install for full details.

    Alternately, add RNBranchModule.setDebug(); in your MainActivity before the call to initSession. Be sure to remove it before releasing to prod.

    // Remove before prod release
    RNBranchModule.setDebug();
    RNBranchModule.initSession(getIntent().getData(), this);

    iOS

    Add [RNBranch setDebug]; or RNBranch.setDebug() in your AppDelegate before the call to initSession. Use conditional compilation or remove before releasing to prod.

    Swift

    #if DEBUG
        RNBranch.setDebug()
    #endif
    RNBranch.initSession(launchOptions: launchOptions, isReferrable: true)

    Objective-C

    #ifdef DEBUG
        [RNBranch setDebug];
    #endif
    [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES];

Using getLatestReferringParams to handle link opens

The getLatestReferringParams method is essentially a synchronous method that retrieves the latest referring link parameters stored by the native SDK. However, React Native does not support synchronous calls to native code from JavaScript, so the method returns a promise. You must await the response or use then to receive the result. The same remarks apply to the getFirstReferringParams method. However, this is only a restriction of React Native. The purpose of getLatestReferringParams is to retrieve those parameters one time. The promise will only return one result. It will not continue to return results when links are opened or wait for a link to be opened. This method is not intended to notify the app when a link has been opened.

To receive notification whenever a link is opened, including at app launch, call branch.subscribe. The callback to this method will return any initial link that launched the app and all subsequent link opens. There is no need to call getLatestReferringParams at app launch to check for an initial link. Use branch.subscribe to handle all link opens.

General troubleshooting

See the troubleshooting guide for each native SDK: