React Native

GitHub 标签(最新日期)GitHub 标签(最新日期)

配置 Branch

安装 Branch

via Pure React Native App

Expo Note: If you are working with Expo, you must first eject your app from Expo, use the Expo Bare Workflow and follow the instructions below.

expo eject

注意: react-native-branch 需要 react-native> = 0.60

  • 安装模块

via Native iOS app with CocoaPods

CocoaPods

platform :ios, '9.0'

target 'APP_NAME' do
  # if swift
  use_frameworks!

  pod 'react-native-branch', path: '../node_modules/react-native-branch'
end
  • 运行 pod install to regenerate the Pods project with the new dependencies. Note that the location of node_modules relative to your Podfile may vary.

📘

(可选)将 branch.json 文件添加到您应用的根目录(package.json 旁边)。

You can configure the contents at any time, but it must be present when you run react-native link in order to be automatically included in your native projects. This allows you to configure certain behaviors that otherwise require native code changes. See https://rnbranch.app.link/branch-json for full details on the branch.json file.

配置应用

iOS

Android

初始化 Branch

iOS

  • In your app's AppDelegate file
import RNBranch

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  
// 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)
  
  return true
}

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

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
  return RNBranch.continue(userActivity)
}
#import "AppDelegate.h"
#import <RNBranch/RNBranch.h>
  
@implementation AppDelegate
  
// 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]; 
    NSURL *jsCodeLocation;
    //...
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    [RNBranch application:app openURL:url options:options]
    return YES;
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
   [RNBranch continueUserActivity:userActivity];
   return YES;
}

@end

Android

  • 将 Branch 添加到您的 MainApplication.java
// import from RNBranch
import io.branch.rnbranch.RNBranchModule;

public class MainApplication extends Application implements ReactApplication {

// add onCreate() override
@Override
public void onCreate() {
  super.onCreate();
  
  // Branch logging for debugging
  RNBranchModule.enableLogging();
  
  RNBranchModule.getAutoInstance(this);
}
// imports from RNBranch
import io.branch.rnbranch.RNBranchModule;
import io.branch.rnbranch.RNBranchPackage;

public class MainApplication extends Application implements ReactApplication {
 
// add RNBranchPackage to react-native package list
@Override
  protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
            new RNBranchPackage(),

// add onCreate() override
@Override
public void onCreate() {
  super.onCreate();
  
  // Branch logging for debugging
  RNBranchModule.enableLogging();
  
  RNBranchModule.getAutoInstance(this);
}
  • 将 Branch 添加到您的 MainActivity.java
import io.branch.rnbranch.*;
import android.content.Intent;

public class MainActivity extends ReactActivity {

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

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

}

实现功能

导入 Branch

  • 在任何使用 Branch SDK 的 React Native 源文件中。
import branch from 'react-native-branch'
Class Declaration
BranchParams L14
BranchEventParams L34
BranchEvent L54
BranchUnsubscribe L215
BranchSubscribe L216
BranchUniversalObjectOptions L220
BranchShareSheetOptions L253
BranchLinkProperties L261
BranchLinkControlParams L270
BranchUniversalObject L279
Branch L294

创建内容参考

let buo = await branch.createBranchUniversalObject('content/12345', {
  title: 'My Content Title',
  contentDescription: 'My Content Description',
  contentMetadata: {
    customMetadata: {
      key1: 'value1'
    }
  }
})

创建深度链接

let linkProperties = {
  feature: 'sharing',
  channel: 'facebook',
  campaign: 'content 123 launch'  
}

let controlParams = {
  $desktop_url: 'https://example.com/home',
  custom: 'data'   
}

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

分享深度链接

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

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

let controlParams = { 
  $desktop_url: 'http://example.com/home', 
  $ios_url: 'http://example.com/ios' 
}

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

读取深度链接

// listener
branch.subscribe(({error, params, uri}) => {
  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

NativeLink™ Deferred Deep Linking

🚧

先决条件

Minimum SDK version: v5.0.4

or

Options for Implementation

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // enable pasteboard check
    [RNBranch.branch checkPasteboardOnInstall]; 
    [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES];

    return YES;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // enable pasteboard check for iOS 15+ only
    if ([[[UIDevice currentDevice] systemVersion] compare:@"15.0" options:NSNumericSearch] != NSOrderedAscending)
        [RNBranch.branch checkPasteboardOnInstall]; 

    [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES];
    
    return YES;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // enable pasteboard check
    [RNBranch.branch checkPasteboardOnInstall];
  
    // check if pasteboard toast will show
    if ([RNBranch.branch willShowPasteboardToast]) {
        // developers can notify the user of what just occurred here if they choose
    }

    [RNBranch initSessionWithLaunchOptions:launchOptions isReferrable:YES];

    return YES;
}

Create QR Code

var qrCodeSettings = {
    width: 500,
    codeColor: "#3b2016",
    backgroundColor: "#a8e689",
    centerLogo: "https://cdn.branch.io/branch-assets/159857dsads5682753-og_image.png",
    margin: 1,
    imageFormat: "PNG"
};

var buoOptions = {
    title: "A Test Title",
    contentDescription: "A test content desc",
    contentMetadata: {
        price: "200",
        productName: "QR Code Scanner",
        customMetadata: { "someKey": "someValue", "anotherKey": "anotherValue" }
    }
};

var lp = {
    feature: "qrCode",
    tags: ["test", "working"],
    channel: "facebook",
    campaign: "posters"
};

var controlParams = {
    $desktop_url: "https://www.desktop.com",
    $fallback_url: "https://www.fallback.com"
};

try {
    var result = await branch.getBranchQRCode(qrCodeSettings, buoOptions, lp, controlParams);
}
catch (err) {
    console.log('QR Code Err: ', err);
}

启用100%匹配

Android

前往内容

branch.subscribe(({error, params, uri}) => {
  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']) {
        // A Branch link opened.
      // Route link based on data in params
      this.navigator.push({params: params, uri: uri})
    return
  }
})

调整缓存的链接 TTL

branch.initSessionTtl = 10000 // Set to 10 seconds
branch.subscribe({ error, params } => {
  // ...
})

追踪用户

branch.setIdentity('theUserId')
branch.logout()

追踪事件

默认情况下,Branch SDK 会自动(不需额外设置)追踪点击,打开,安装,重新安装和展示。

Please refer to our Event Tracking Docs for more information and examples:

在应用中处理深度链接

branch.openURL("https://example.app.link/u3fzDwyyjF")
branch.openURL("https://example.app.link/u3fzDwyyjF", {newActivity: true}) // Finish the Android current activity before opening the link. Results in a new activity window. Ignored on iOS.

❗️

处理新的深度链接

在应用中处理新的深度链接将清除当前会话数据,并将新引用的 “open” 归因于此。

处理推送通知

Allows you to track Branch deep links in your push notifications.

Please refer to our Native SDK Documentation:

设置初始化 metadata

If you are using a 3rd Party Data Integration Partner that requires setting certain identifiers before initializing the Branch SDK, you should add this code snippet:

RNBranch.setRequestMetadataKey("{ANALYTICS_ID}", "…")
[[RNBranch getInstance] setRequestMetadataKey:@"{ANALYTICS_ID}" value: […]];
RNBranchModule.setRequestMetadata("{ANALYTICS_ID}", "…");

在打开链接之前接收通知

需要 react-native-branch 5.x

To be notified that Branch is about to open a link, use an onOpenStart callback with branch.subscribe. Also supply an onOpenComplete callback, which is the same as the single callback usually used with branch.subscribe

import branch from 'react-native-branch';

branch.subscribe({
  onOpenStart: ({uri, cachedInitialEvent}) => {
    // cachedInitialEvent is true if the event was received by the
    // native layer before JS loaded.
    console.log('Branch will open ' + uri);
  },
  onOpenComplete: ({error, params,uri}) => {
    if (error) {
      console.error('Error from Branch opening uri ' + uri);
      return;
    }

    console.log('Branch opened ' + uri);
    // handle params
  },
})

请注意,在某些情况下,uri 将为 null,特别是在延迟深度链接的情况下。在这些情况下,请检查〜referring_link,+ url 或 +non_branch_link 的参数以确定引用 URL/URL。

排查问题

Please refer to out Native SDK Docs:

使用 getLatestReferringParams 处理链接打开

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.

常见的构建问题

-dontwarn com.crashlytics.android.answers.shim.**
-dontwarn com.google.firebase.appindexing.**

常规问题排查

请参阅每个原生 SDK 的问题排查指南:

示例应用

Updated 16 days ago


这个页面对您有帮助吗?