Capacitor

npmnpm

安装 Branch

npm install capacitor-branch-deep-links

配置 Branch

23642364

配置应用

Android

  • If your app is in the Google Play Store, update build.gradle with the necessary dependencies:
apply plugin: 'com.android.application'

android {
    defaultConfig {
        // ...
+       multiDexEnabled true
        // ...
    }
}

dependencies {
+    implementation 'com.android.support:multidex:1.0.3'

+    // Branch: required if your app is in the Google Play Store (tip: avoid using bundled play services libs)
+    implementation 'com.google.firebase:firebase-appindexing:19.1.0' // App indexing
+    implementation 'com.google.android.gms:play-services-ads:19.4.0' // GAID matching

+    // Branch: optional
+    implementation 'androidx.browser:browser:1.2.0' // Chrome Tab matching (enables 100% guaranteed matching based on cookies)
+    // Replace above with the line below if you do not support androidx
+    // implementation 'com.android.support:customtabs:28.0.0'
}
  • Update src/main/res/values/strings.xml with your configuration:
<?xml version='1.0' encoding='utf-8'?>
  <resources>
      <!-- ... ->
+     <string name="applink_host">example.app.link</string>
+     <string name="applink_host_alternate">example-alternate.app.link</string>
+     <string name="deeplink_scheme">example</string>
+     <string name="branch_key">key_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</string>
+     <string name="branch_test_key">key_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</string>
+     <bool name="branch_test_mode">false</bool>
+     <!-- set above to "true" to use test key -->
  </resources>
  • Register the plugin in your Activity and set the RequestMetaDataKey
package com.example;

+ import android.content.Intent;
import android.os.Bundle;
+ import co.boundstate.BranchDeepLinks;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;
import java.util.ArrayList;
+ import io.branch.referral.Branch;

public class MainActivity extends BridgeActivity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
+   Branch.getInstance().setRequestMetadataKey("insert_user_id", "value"); // if you need to append partner metadata before initializing Branch
+   registerPlugin(BranchDeepLinks.class);
  }
+
+  @Override
+  protected void onNewIntent(Intent intent) {
+    this.setIntent(intent);
+    super.onNewIntent(intent);
+  }
}
  • Add a CustomApplicationClass.java to your project with the following content:
+ package com.example;
+
+ import android.content.Context;
+ import android.os.UserManager;
+ import androidx.multidex.MultiDex;
+ import androidx.multidex.MultiDexApplication;
+ import static android.os.Build.VERSION.SDK_INT;
+ import io.branch.referral.Branch;
+
+ public class CustomApplicationClass extends MultiDexApplication {
+
+   @Override
+   public void onCreate() {
+     super.onCreate();
+
+     // Branch logging for debugging
+     Branch.enableLogging();
+
+     if (SDK_INT >= 24) {
+       UserManager um = getApplicationContext().getSystemService(UserManager.class);
+       if (um == null || !um.isUserUnlocked()) return;
+     }
+
+     // Branch object initialization
+     Branch.getAutoInstance(this);
+   }
+
+   @Override
+   protected void attachBaseContext(Context base) {
+     super.attachBaseContext(base);
+     MultiDex.install(this);
+   }
+ }
  • 如下更新您的 Android Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example">

    <application
+       android:name=".CustomApplicationClass"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!-- ... -->

+       <meta-data
+           android:name="com.google.android.gms.ads.AD_MANAGER_APP"
+           android:value="true"/>

        <activity
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
            android:name="com.example.MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBarLaunch"
            android:launchMode="singleTask">

+           <intent-filter>
+               <action android:name="android.intent.action.MAIN" />
+               <category android:name="android.intent.category.LAUNCHER" />
+           </intent-filter>

+           <!-- BEGIN BRANCH -->
+           <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="http"
+                   android:host="@string/applink_host" />
+               <data
+                   android:scheme="https"
+                   android:host="@string/applink_host" />
+               <data
+                   android:scheme="http"
+                   android:host="@string/applink_host_alternate" />
+               <data
+                   android:scheme="https"
+                   android:host="@string/applink_host_alternate" />
+           </intent-filter>
+
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
-               <data android:scheme="@string/custom_url_scheme"/>
+               <data android:scheme="@string/deeplink_scheme"/>
            </intent-filter>
+           <!-- END BRANCH -->

        </activity>

+       <!-- BEGIN BRANCH -->
+       <!-- Branch init -->
+       <meta-data android:name="io.branch.sdk.BranchKey" android:value="@string/branch_key" />
+       <meta-data android:name="io.branch.sdk.BranchKey.test" android:value="@string/branch_test_key" />
+       <meta-data android:name="io.branch.sdk.TestMode" android:value="@bool/branch_test_mode" />
+       <!-- END BRANCH -->
+
        <!-- ... -->

    </application>

    <!-- ... -->

</manifest>

iOS

📘

iOS 14 实施

为了帮助您全面管理用户体验,Branch SDK 将不会触发 IDFA 许可弹窗。

然而,如果您选择触发这一弹窗,在可行的情况下,Branch 仍然可以收集并使用 IDFA。

了解更多

  1. 配置 Bundle ID
  2. 配置 Associated Domain
  3. 配置权利
  4. 配置 Info.plist
  • 更新项目:
npx cap update ios

Make the following changes to your AppDelegate.swift file:

import UIKit
import Capacitor
+import Branch

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
+       Branch.setUseTestBranchKey(true) // if you are using the TEST key
+       Branch.getInstance().enableLogging() // enable logging
+       Branch.setRequestMetadataKey("insert_user_id", "value") //if you need to append partner metadata before initializing Branch      
+       Branch.getInstance().initSession(launchOptions: launchOptions)
        
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        // Called when the app was launched with a url. Feel free to add additional processing here,
        // but if you want the App API to support tracking app url opens, make sure to keep this call
+       Branch.getInstance().application(app, open: url, options: options)
        return ApplicationDelegateProxy.shared.application(app, open: url, options: options)
    }

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // Called when the app was launched with an activity, including Universal Links.
        // Feel free to add additional processing here, but if you want the App API to support
        // tracking app url opens, make sure to keep this call
 +      Branch.getInstance().continue(userActivity)
        return ApplicationDelegateProxy.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
    }

        if statusBarRect.contains(touchPoint) {
            NotificationCenter.default.post(name: .capacitorStatusBarTapped, object: nil)
        }
    }
    
+   func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
+        Branch.getInstance().handlePushNotification(userInfo)
+     }

}

初始化 Branch

+ import { Plugins } from '@capacitor/core';
+ import { BranchInitEvent } from 'capacitor-branch-deep-links';

+ const { BranchDeepLinks } = Plugins;

  @Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
  })
  export class AppComponent {
    constructor(
      private platform: Platform,
      private splashScreen: SplashScreen,
      private statusBar: StatusBar
    ) {
      this.initializeApp();
    }

    initializeApp() {
      this.platform.ready().then(() => {
        this.statusBar.styleDefault();
        this.splashScreen.hide();
+       BranchDeepLinks.addListener('init', (event: BranchInitEvent) => {
+         // Retrieve deeplink keys from 'referringParams' and evaluate the values to determine where to route the user
+         // Check '+clicked_branch_link' before deciding whether to use your Branch routing logic
+         console.log(event.referringParams);
+       });

+       BranchDeepLinks.addListener('initError', (error: any) => {
+         console.error(error);
+       });
      });
    }
  }

实现功能

创建深度链接

// optional fields
var analytics = {
  channel: 'facebook',
  feature: 'onboarding',
  campaign: 'content 123 launch',
  stage: 'new user',
  tags: ['one', 'two', 'three']
}

// optional fields
var properties = {
  $desktop_url: 'http://www.example.com/desktop',
  $android_url: 'http://www.example.com/android',
  $ios_url: 'http://www.example.com/ios',
  $ipad_url: 'http://www.example.com/ipad',
  $match_duration: 2000,
  custom_string: 'data',
  custom_integer: Date.now(),
  custom_boolean: true
}

BranchDeepLinks.generateShortUrl({ analytics, properties }).then(function (res) {
  alert('Response: ' + JSON.stringify(res.url))
}).catch(function (err) {
  alert('Error: ' + JSON.stringify(err))
})

分享深度链接

  • 生成 Branch 深度链接,并通过用户选择的渠道对其进行标签

  • Uses Deep Link Properties

// optional fields
var analytics = {
  channel: 'facebook',
  feature: 'onboarding',
  campaign: 'content 123 launch',
  stage: 'new user',
  tags: ['one', 'two', 'three']
}

// optional fields
var properties = {
  $desktop_url: 'http://www.example.com/desktop',
  custom_string: 'data',
  custom_integer: Date.now(),
  custom_boolean: true
}

var shareText = 'Check out this link'

// share sheet
BranchDeepLinks.showShareSheet({ analytics, properties, shareText })

NativeLink™ Deferred Deep Linking (iOS Only)

  • Use iOS pasteboard to enable deferred deep linking via Branch NativeLink™

🚧

先决条件

Make sure the underlying iOS SDK Version is v1.39.4+

To use this feature you must:

Implement one of the pasteboard opt-in options in the native iOS SDK code.

Create QR Code

  • Set your Qr Code Settings

  • Set your Analytics and Link Properties

  • Use getBranchQRCode() to create a QR code.

// optional fields
    var analytics = {
      channel: 'facebook',
      feature: 'onboarding',
      campaign: 'content 123 launch',
      stage: 'new user',
      tags: ['one', 'two', 'three']
    }

    // optional fields
    var properties = {
      $desktop_url: 'http://www.example.com/desktop',
      $android_url: 'http://www.example.com/android',
      $ios_url: 'http://www.example.com/ios',
      $ipad_url: 'http://www.example.com/ipad',
      $match_duration: 2000,
      custom_string: 'data',
      custom_integer: Date.now(),
      custom_boolean: true
    }

    var settings = {
      width: 2000,
      codeColor: "#3b2016",
      backgroundColor: "#c79200",
      centerLogo: "https://cdn.britannica.com/95/156695-131-FF89C9FA/oak-tree.jpg",
      margin: 3,
      imageFormat: "PNG"
    }

    BranchDeepLinks.getBranchQRCode({analytics, properties, settings}).then((res) => {
      this.picToView  = "data:image/png;base64," + res.qrCode;
    }).catch(function (err) {
      alert('Error getting QR code: ' + JSON.stringify(err) + err)
    })

Learn more from our QR Code API

追踪用户

  • Sets the identity of a user (ID, UUID, etc) for events, deep links, and referrals

  • Validate with the Branch Dashboard

var newIdentity = '123456'
BranchDeepLinks.setIdentity({ newIdentity }).then(function (res) {
  alert('Response: ' + JSON.stringify(res.referringParams))
}).catch(function (err) {
  alert('Error: ' + JSON.stringify(err))
})
  • 删除用户身份
BranchDeepLinks.logout().then(function (res) {
  alert('Response: ' + JSON.stringify(res.logged_out))
}).catch(function (err) {
  alert('Error: ' + JSON.stringify(err))
})

追踪事件

  • 注册自定义事件

  • Events named opencloseinstall, and referred session are Branch restricted

  • Best to Track users before Track events to associate a custom event to a user

  • Validate with the Branch Dashboard

var eventName = 'clicked_on_this'
var metaData = { 'custom_dictionary': 123, 'anything': 'everything' }
BranchDeepLinks.sendBranchEvent({ eventName, metaData })

var eventName = 'clicked_on_this'
BranchDeepLinks.sendBranchEvent({ eventName })

追踪 commerce

// get a list of all Branch standard events
BranchDeepLinks.getStandardEvents().then(function (res) {
  alert('Response: ' + JSON.stringify(res.branch_standard_events))
}).catch(function (err) {
  alert('Error: ' + JSON.stringify(err))
})

var eventName = 'ADD_TO_CART'
var metaData = {
  customerEventAlias: 'alias name for event',
  transactionID: '1234455',
  currency: 'USD',
  revenue: 1.5,
  shipping: 10.2,
  tax: 12.3,
  coupon: 'test_coupon',
  affiliation: 'test_affiliation',
  description: 'Test add to cart event',
  searchQuery: 'test keyword',
  customData: {
    "Custom_Event_Property_Key1": "Custom_Event_Property_val1",
    "Custom_Event_Property_Key2": "Custom_Event_Property_val2"
  }
}

BranchDeepLinks.sendBranchEvent({ eventName, metaData })

禁用追踪

如果您需要按照 GDPR 的目的遵循用户不被追踪的请求,或者认为用户不应该被追踪,请利用此字段来防止 Branch 发送网络请求。此设置也可以在所有用户的特定链接或 Branch Link 中被启用。

BranchDeepLinks.disableTracking().then(function (res) {
  alert('Response: ' + JSON.stringify(res.is_enabled))
}).catch(function (err) {
  alert('Error: ' + JSON.stringify(err))
})

var isEnabled = true
BranchDeepLinks.disableTracking({ isEnabled }).then(function (res) {
  alert('Response: ' + JSON.stringify(res.is_enabled))
}).catch(function (err) {
  alert('Error: ' + JSON.stringify(err))
})

这个页面对您有帮助吗?