DEV Community

Subramanya Chakravarthy
Subramanya Chakravarthy

Posted on

Integrating Branch in React Native > 0.60

What is Deep Linking?

Deeplinks are a concept that help users navigate between the web and applications. They are basically URLs which navigate users directly to the specific content in applications.

Deep Links are nicest addition to your apps, as your users can navigate to the required content without any hassle.

Branch is one the providers which provide contextual deep links. Contextual deep links store information about where a user wants to go, where the link was clicked, who originally shared the link, and an almost unlimited amount of custom data.

It also has Deferred deep link functionality. Deferred deep links can route users to content even if the app is not installed when the link is opened. The link will first redirect to the App Store or Play Store to download the app, and then take the user to the specific “deferred” content immediately after first launch.

This guide is for React Native >= 0.60

In Branch Dashboard create a new app

Create Branch App

The Basics

Let's start by adding Branch to our react native project

npm

npm i react-native-branch

yarn

yarn add react-native-branch

Create a JSON file with name branch.json at top of your project directory (next to package.json). Here's the dummy contents of the file

{
    "debugMode": true,
    "liveKey": "key_live_******",
    "testKey": "key_test_******",
    "useTestInstance": true,
    "delayInitToCheckForSearchAds": true,
    "appleSearchAdsDebugMode": true
}

Get your livekey and testkey from Account Settings

Let’s setup iOS

  • Add this line to your Podfile located in ios folder

    pod "react-native-branch", path: "../node_modules/react-native-branch"

  • Run pod install to regenerate the Pods project with the new dependencies.

Click on Set up SDK in Branch dashboard and select iOS

Let's do some Xcode 💻

  • In your Xcode project general tab, you will find Bundle Identifier Xcode Project
  • Find Apple App Prefix here. If you don't see your app create one from Identifiers
  • Give a URI Scheme something like mysuperapp://
  • Configure Associated Domains
    • In Xcode open Signing and Capabilities tab, and click on Add Capability. Then choose Associated Domains
    • Add Branch Domains from Dashboard Xcode Associated Domains
  • Now Go to Build Phases and expand Copy Bundle Resources, now Add YourApp.entitlements Entitlements
  • Right click your Info.plist file and select Open As > Source code and add branch specific code. Now change the Branch key, app_domain and Url Scheme from dashboard

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
        <dict>
        ...
        <key>branch_key</key>
        <string>key_live_******</string>
        <key>branch_app_domain</key>
        <string>9jzhz.app.link</string>
        <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleURLSchemes</key>
                <array>
                    <string>branchapp</string>
                </array>
            </dict>
        </array>
        ...
        </dict>
    </plist>
    
  • Initialize Branch
    Open AppDelegate.m and add the following code

    #import <RNBranch/RNBranch.h>
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {   
        //  Branch
        [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES];
    
        RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
        RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                                                                        moduleName:@"BranchExample"
                                                                                            initialProperties:nil];
    
        rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
    
        self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        UIViewController *rootViewController = [UIViewController new];
        rootViewController.view = rootView;
        self.window.rootViewController = rootViewController;
        [self.window makeKeyAndVisible];
        return YES;
    }
    
    - (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];
    }
    
    

Let's setup Android

  • Select enable app links
    You can get your App's SHA256 from this command and then add it to Dashboard

    Android sha 256

    keytool -list -v -keystore <keystore path> -alias <key alias> -storepass <store password> -keypass <key password>

  • Add uri scheme again, this time it's for android

  • Open MainApplication.java and add following code

  • Configure Manifest (AndroidMAnifest.xml)

    • For the MainActivity add android:launchMode="singleTask"
    • Also these intent filters
    <!-- Branch URI scheme -->
    <intent-filter>
            <data android:scheme="branchapp" android:host="open" />
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
    </intent-filter>

    <!-- Branch App Links -->
    <intent-filter android:autoVerify="true">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="https" android:host="9jzhz.app.link" />
    </intent-filter>
    ```


  * Add these metadata to your application


  ```xml
    <!-- Branch init -->
    <meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_******" />
    <!-- Branch testing (TestMode "true" to simulate fresh installs on dev environment) -->
    <meta-data android:name="io.branch.sdk.TestMode" android:value="false" />
    ```


  * And a receiver


  ```xml
    <!-- Branch install referrer tracking -->
    <receiver android:name="io.branch.referral.InstallListener" android:exported="true">
            <intent-filter>
                <action android:name="com.android.vending.INSTALL_REFERRER" />
            </intent-filter>
    </receiver>
    ```


    * android/app/proguard-rules.pro
  `-dontwarn io.branch.**`

    * In MainApplication.java



        ```java
        @Override
        public void onCreate() {
            super.onCreate();
            SoLoader.init(this, /* native exopackage */ false);
            RNBranchModule.getAutoInstance(this);
        }
        ```


    * In MAinActivity.java



        ```java
        @Override
        protected void onStart() {
                super.onStart();
                RNBranchModule.initSession(getIntent().getData(), this);
        }

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



# Let's Implement some Features 

First we create a Branch Universal Object with the content to share and call a Branch function to generate a short deep link url for sharing



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

// only canonicalIdentifier is required
let branchUniversalObject = await branch.createBranchUniversalObject('canonicalIdentifier', {
  locallyIndex: true,
  title: 'Cool Content!',
  contentDescription: 'Cool Content Description',
  contentMetadata: {
    ratingAverage: 4.2,
    customMetadata: {
      prop1: 'test',
      prop2: 'abc'
    }
  }
})

let linkProperties = {
    feature: 'share',
    channel: 'facebook'
}

let controlParams = {
     $desktop_url: 'http://desktop-url.com/monster/12345'
}

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

Branch Provides Share functionality which automaically generates deep link url and opens Share Sheet

let shareOptions = { messageHeader: 'Check this out', messageBody: 'No really, check this out!' }
let linkProperties = { feature: 'share', channel: 'RNApp' }
let controlParams = { $desktop_url: 'http://example.com/home', $ios_url: 'http://example.com/ios' }
let {channel, completed, error} = await branchUniversalObject.showShareSheet(shareOptions, linkProperties, controlParams)

Listening to Deep Links

In your App.js ComponentDidMount create a subscriber to listen

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

  // params will never be null if error is null
})

let lastParams = await branch.getLatestReferringParams() // params from last open
let installParams = await branch.getFirstReferringParams() // params from original install

Navigate to screen based on the data

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, e.g.

  // Get title and url for route
  const title = params.$og_title
  const url = params.$canonical_url
  const image = params.$og_image_url

  // Now push the view for this URL
  this.navigator.push({ title: title, url: url, image: image })
})

That's it you have successfully configured Branch . If you find this article helpful please show your love by sharing it.

Top comments (4)

Collapse
 
priyabapodra profile image
Priya Bapodra

Hello, can you please specify how to get canonicalIdentifier for react native ?
please tell me i am working on it

Collapse
 
rajkamalagicent profile image
Rajkamal Singh

what can i add in android uri scheme at Branch dashboard

Collapse
 
starryfire profile image
Kartik Sharma

Can you please tell me how to integrate branch.io with React-navigation library?

Collapse
 
ghana7989 profile image
ghana

reactnavigation.org/docs/deep-link...
pass this linking object to NavigationContainer's linking property