iOS 完整参考
可用于 CocoaPods
Branch is available through CocoaPods. To install it, simply add the following line to your Podfile:
// iOS SDK 2.0.0+
pod 'BranchSDK'
// iOS SDK <2.0.0
// pod 'Branch'
Then, from the command line, cd
to your project directory, and do:
pod install
pod update
安装 Branch pod 并将其更新到最新版本的 SDK。
Make sure to do the pod update
. CocoaPods may not use the latest version of the SDK otherwise!
Carthage
To integrate Branch into your project using Carthage add the following to your Cartfile
:
github "BranchMetrics/ios-branch-deep-linking"
下载原始文件
您也可以通过下载以下原始文件进行安装。
- Download code from here:
https://s3-us-west-1.amazonaws.com/branchhost/Branch-iOS-SDK.zip - The testbed project:
https://s3-us-west-1.amazonaws.com/branchhost/Branch-iOS-TestBed.zip
将 Raw Files Branch SDK 添加到您的项目
如果您不想通过 Cocoapods 或 Carthage 而直接添加 Branch SDK,请将Branch 作为动态框架依赖项添加到项目中。
我将 Branch 添加到 “BareBones” 项目作为示例:
- 下载或克隆 Branch SDK 文件到您的计算机。
- 如果您已经将 Branch 添加到您的项目中,请将其删除。
- In the Xcode project navigator view, select your project, right-click, and select 'Add files to "<your project name>"...'

Add Files...
- “Add” 文件选择器将打开。前往 “ios-branch-deep-linking>carthage-files 目录,然后选择 BranchSDK.xcodeproj 项目。

Add BranchSDK.xcodeproj
Xcode 会将 BranchSDK.xcodeproj 添加到您的项目中。
- 在您的项目中,显示 "BranchSDK.xcodeproj>Product" 层次结构。然后将 Branch.framework 产品拖动到构建产品的 “Embedded Binaries” 部分。

Embed Binary
- 完成!您可以点击项目的“构建阶段”,以确保 Branch 作为目标依赖项(Target Dependency)添加,并作为嵌入式框架(Embedded Framework)复制。
注册您的应用
You can sign up for your own app id at https://dashboard.branch.io.
将您的 Branch key 添加到您的项目中
After you register your app, your Branch Key can be retrieved on the Settings page of the dashboard. Now you need to add it to YourProject-Info.plist (Info.plist for Swift).
- 在 plist 文件中,将鼠标悬停在“信息属性列表(Information Property List)”上,这是 Key 列下的根项目。
- 大约半秒钟后,您将看到一个“ +”号出现。点击它。
3 在新添加的行中,为其 key 填写 “branch_key”,将类型保留为 String,然后在值列中输入在上述步骤中获得的应用的 Branch key。 - 保存 plist 文件。
如果要同时为动态和测试应用添加 key,则需要将类型列更改为 Dictionary,并在其中添加两个条目:
- 对于动态应用,将 "live"(不带双引号)用于 key,将 String 用于类型,将 live branch key 用于值。
- 对于测试应用,将 "test"(不带双引号)用于 key,将 String 用于类型,将 test branch key 用于值。
注意
If you used Fabric to install Branch as a kit, your Branch keys will be in your Info.plist as an element under the Fabric > Kits array, as shown below.
注册 URI Scheme
通过在 YourProject-Info.plist 文件中添加 URI scheme,注册您的应用以响应直接深度链接(在移动浏览器中为 yourapp://)。确保将 yourapp 更改为代表应用名称的唯一 string。
- 在 Xcode 中,点击左侧的 YourProject-Info.plist。
- 查找 URL 类型,然后点击右箭头。 (如果不存在,请右键点击任意位置,然后选择添加行(Add Row)。向下滚动并选择 URL 类型)。
- 添加 “yourapp” 作为 URL Scheme 的一项,其中 yourapp 是应用的唯一 string。
警告
Your apps URI scheme must be the first scheme defined (item 0) in the list
如果您定义了多个方案,例如 Facebook login URI,请使您的应用的 URI scheme 成为列表中的第一个方案,以便 Branch SDK 知道特定于应用的 URI。

URL Scheme Demo
或者,您可以在项目的信息(Info)页面中添加 URI scheme。
- 在 Xcode 中,在 Navigator(左侧)点击您的项目。
- 选择"信息(Info)"标签。
- 展开底部的 "URL Types" 部分。
- 点击"+"符号以添加新的 URI scheme,如下所示:

URL Scheme Demo
支持 Universal Linking(iOS 9及更高版本)
在 iOS 9中,Apple 添加了一种功能,可允许 http 链接直接打开您的应用,而不是通过 URI Scheme。这设置起来会很麻烦,因为它在服务器上涉及到很复杂的过程。好消息是,Branch 仅需两个步骤即可为您完成这项工作!
- 在 Xcode 中,在 Navigator(左侧)点击您的项目。
- 选择"功能(Capabilities)"选项卡。
- 展开 "Associated Domains" 选项卡。
- 启用设置(切换开关)。
- 添加
applinks:xxxx.app.link
andapplinks:xxxx-alternate.app.link
to the list. Make surexxxx
matches the 4 character subdomain for your app (you can find it on the dashboard here). If you use a custom subdomain, use that in place of the x's (egimgur.app.link
andimgur-alternate.app.link
). - Add any additional custom domains you have (e.g.
applinks:vng.io
)
- 在操作后台 (Dashboard),前往应用的链接设置页面。
- 选中"启用 Universal Link
- 确保您的 Apple Team ID 和 App Bundle ID 是正确的(我们会尝试自动为您收集它们)。
- 确保保存这些设置更新。
自定义域名配置(如果您不使用 Branch 提供的 xxxx.app.link 域,则为必填项)
Branch 为您的应用提供了一个 xxxx.app.link 域,但是您可以使用自己的自定义域来创建 app link。如果您确实要将自己的自定义域用于 universal app link,则需要将其添加到 Info.plist。
Add the branch_universal_link_domains
key with your custom domain as a string value:
URI Scheme 注意事项
The Branch SDK will pull the first URI Scheme from your list that is not one of fb
, db
, or pin
. This value will be used one time to set the iOS URI Scheme under your Link Settings in the Branch Dashboard.
For additional help configuring the SDK, including step-by-step instructions, please see the iOS Quickstart Guide.
获取 Singleton Branch 实例
所有 Branch 方法都需要 Branch 主要对象的实例。下面将说明您如何将其获取。它是静态存储的,可以从任何类访问。
Branch *branch = [Branch getInstance];
let branch: Branch = Branch.getInstance()
测试
测试您的 Branch 集成
通过调用。。。来测试您的 Branch 集成 validateSDKIntegration
in your AppDelegate. Check your Xcode logs to make sure all the SDK Integration tests pass. Make sure to comment out or remove validateSDKIntegration
in your production build.
Branch.getInstance().validateSDKIntegration()
[[Branch getInstance] validateSDKIntegration];
测试 Branch Link 的深度链接路由
Append ?bnc_validate=true
to any of your app's Branch links and click it on your mobile device (not the Simulator!) to start the test. For instance, to validate a link like: "https://<yourapp\>.app.link/NdJ6nFzRbK"
click on: "https://<yourapp\>.app.link/NdJ6nFzRbK?bnc_validate=true"
//TODO: Remove for launch
Branch.setUseTestBranchKey(true)
#warning Remove for launch
[Branch setUseTestBranchKey:YES];
参数
Branch key(NSString *)可选:
如果不把 Branch key 存储在 plist 文件中,您可以选择将它作为参数传递。
初始化 Branch 会话和深度链接路由功能
要进行深度链接,Branch 必须初始化会话以检查用户是否源自链接。每次打开应用时,此调用都会初始化一个新的会话 。在应用打开的时间中,有100%的时间,它将调用深度链接处理块来通知您用户是否源自链接。如果您的应用打开时在参数中带有 key,您则需要根据传入的数据来路由用户。否则,请将其发送到通用屏幕。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let branch: Branch = Branch.getInstance()
branch?.initSession(launchOptions: launchOptions, deepLinkHandler: { params, error in
if error == nil {
// params are the deep linked params associated with the link that the user clicked -> was re-directed to this app
print("params: %@", params.description)
}
})
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
// Pass the url to the handle deep link call
let branchHandled = Branch.getInstance().application(
application,
open: url,
options: options
)
if (!branchHandled) {
// If not handled by Branch, do other deep link routing for the
// Facebook SDK, Pinterest SDK, etc
}
return true
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
let handledByBranch = Branch.getInstance().continue(userActivity)
return handledByBranch
}
func application(_ application: UIApplication, didReceiveRemoteNotification launchOptions: [AnyHashable: Any]) -> Void {
Branch.getInstance().handlePushNotification(launchOptions)
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
Branch *branch = [Branch getInstance];
[branch initSessionWithLaunchOptions:launchOptions andRegisterDeepLinkHandler:^(NSDictionary *params, NSError *error) {
// route the user based on what's in params
}];
return YES;
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
BOOL branchHandled =
[[Branch getInstance]
application:application
openURL:url
options:options];
if (!branchHandled) {
// do other deep link routing for the Facebook SDK, Pinterest SDK, etc
}
return YES;
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> *restorableObjects))restorationHandler {
BOOL handledByBranch = [[Branch getInstance] continueUserActivity:userActivity];
return handledByBranch;
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[[Branch getInstance] handlePushNotification:userInfo];
}
注意:如果您的应用委托声明了该方法:
optional func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool
- (BOOL) application:willFinishLaunchingWithOptions:
it must return YES
for Branch to work.
参数
initSession
initSession
参数 | 描述 | 必要项 |
---|---|---|
launchOptions (NSDictionary *) | 这些启动选项通过 didFinishLaunchingWithOptions 传递给 Branch,并将通知我们用户是否来自 URI 调用。如果应用是通过 myapp://之类的 URI 打开的,我们则需要遵循特殊的初始化例程。 | Y |
deepLinkHandler ^(NSDictionary params, NSError error) | This is the callback block that Branch will execute after a network call to determine where the user comes from. It is called 100% of the time the app opens up since Branch registers for lifecycle notifications. NSDictionary *params : These params will contain any data associated with the Branch link that was clicked before the app session began. There are a few keys which are always present: - '+isfirst_session' Denotes whether this is the first session (install) or any other session (open) - '+clicked_branch_link' Denotes whether or not the user clicked a Branch link that triggered this session _NSError *error : This error will be nil unless there is an error such as connectivity or otherwise. Check !error to confirm it was a valid link. - BNCServerProblemError There was an issue connecting to the Branch service - BNCBadRequestError The request was improperly formatted | N |
isReferrable (BOOL) | This boolean lets you control whether or not the user is eligible to be 'referred'. This is applicable for credits and influencer tracking. If isReferrable is set to NO | false, and the user clicks a link before entering the app, deep link parameters will appear, but that user will not be considered referred. If isReferrable is set to YES | true, and the user clicks a link, deep link params will appear and the user will be considered referred. Remove this argument to access the default, which only allows the user to be referred on a fresh install, but not on opens. | N |
automaticallyDisplayDeepLinkController (BOOL) | This boolean lets you control whether or not the Branch should attempt to launch Deep Linked controllers (based on those registered with [branch registerDeepLinkController:forKey:] ). The default is NO | false. | N |
Branch 每次都返回显式参数。这里有一个列表,以及与其相对应的描述。
~
表示分析+
表示 Branch 添加的信息- (for the curious,
$
denotes reserved keywords used for controlling how the Branch service behaves)
参数 | 描述 |
---|---|
~channel | 在创建链接时指定共享链接的渠道 |
~feature | The feature, such as invite or share , specified at link creation time |
~tags | 在链接创建时指定的任何标签 |
~campaign | 与链接关联的 Campaign,在链接创建时指定 |
~stage | 在链接创建时指定的阶段 |
~creation_source | 链接创建位置 ('API', 'Dashboard', 'SDK', 'iOS SDK', 'Android SDK', 或 'Web SDK') |
+match_guaranteed | 关于匹配是否以100%的准确性进行的判断是对还是错 |
+referrer | 点击链接的推荐人来源网址(如果已点击链接) |
+phone_number | 用户的电话号码(如果用户通过短信将应用发送给自己) |
+is_first_session | 表示这是第一个会话(安装)还是任何其他会话(打开) |
+clicked_branch_link | 表示用户是否点击了触发该会话的 Branch Link |
+click_timestamp | 点击发生的时间戳记 |
handleDeepLink
handleDeepLink
参数 | 描述 | 必要项 |
---|---|---|
url (NSString *) | 此参数给我们传递 URI string,以便我们可以解析额外的参数。例如,“ myapp://open?link_click_id=12345”。 | Y |
continueUserActivity
continueUserActivity
参数 | 描述 | 必要项 |
---|---|---|
userActivity (NSUserActivity *) | 此参数给我们传递用户活动,以便我们可以解析原始 URL。 | Y |
Returns
handleDeepLink
handleDeepLink
BOOL handleDeepLink 将返回一个布尔值,指示 Branch 是否已处理 URI。如果 URI 调用是 'myapp://open?link_click_id=12345' ,则 handleDeepLink 将返回 YES,因为存在 Branch 点击对象。如果只有 'myapp://' ,handleDeepLink 将返回 NO。
continueUserActivity
continueUserActivity
BOOL continueUserActivity 将返回一个布尔值,指示 Branch 是否已处理 Universal Link。如果 Universal Link 由 Branch 提供支持,则由于存在 Branch 点击对象,continueUserActivity 将返回 YES。
If you use your own custom universal link domain, make sure you add it your Info.plist under the branch_universal_link_domains
key as described here or this method may erroneously return NO
when in fact the universal link will be opened.
注册深度链接控制器
Register a controller for Branch to show when specific keys are present in the Branch open / install dictionary. This is the mechanism to handle auto deep linking and should be called before initSession
。
Branch.getInstance().registerDeepLinkController(myController forKey:"my-key" withPresentation: .optionShow)
[[Branch getInstance] registerDeepLinkController:myController forKey:@"my-key" withPresentation:BNCViewControllerOptionShow];
参数
参数 | 描述 | 必要项 |
---|---|---|
controller (UIViewController *) | 当字典中存在 key 时显示的控制器。 | Y |
key (NSString *) | 在 open/install 库中检查的 key。 | Y |
Option (BNCViewControllerPresentationOption) | BNCViewControllerOptionShow: This option pushes view controller onto the navigation stack in a similar way as the showViewController BNCViewControllerOptionPush: This option pushes view controller onto the navigation stack in a similar way as the pushViewController BNCViewControllerOptionPresent : This option presents view controller onto the root view controller of window in a similar way as the presentViewController | Y |
获得会话(安装或打开)参数
这些会话参数在此命令之后随时可用。如果没有可用参数,则 Branch 将返回一个空字典。这会刷新每一次的新会话(应用安装和应用打开)。
警告
If the Branch SDK is retrieving the latest session parameters via a network call, this method will return the previous session's parameters. The best practice is to set a callback deep link handler at Branch initialization. That handler will be called when a Branch deep link is handled, and the most recent session parameters are available.
Otherwise, use the getLatestReferringParamsSynchronous
method. This method always returns the latest session parameters. The downside is that it may block the calling thread until the current results are available.
// This is an example of `getLatestReferringParams`.
// Warning: It may return the previous results.
let sessionParams = Branch.getInstance().getLatestReferringParams()
// This is an example of `getLatestReferringParamsSynchronous`.
// Warning: It may block the current thread until the latest results are available.
let sessionParams = Branch.getInstance().getLatestReferringParamsSynchronous()
// This is an example of `getLatestReferringParams`.
// Warning: It may return the previous results.
NSDictionary *sessionParams = [[Branch getInstance] getLatestReferringParams];
// This is an example of `getLatestReferringParamsSynchronous`.
// Warning: It may block the current thread until the latest results are available.
NSDictionary *sessionParams = [[Branch getInstance] getLatestReferringParamsSynchronous];
Returns
NSDictionary*
当 initSession 返回在深度链接回调中设置的参数时,我们会在会话期间将其存储在 NSUserDefaults 中,以备日后获得时使用。请注意,一旦应用被最小化并且会话结束后,它将被清除。
获得安装(仅安装)参数
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.
let installParams = Branch.getInstance().getFirstReferringParams() // previously getInstallReferringParams
NSDictionary *installParams = [[Branch getInstance] getFirstReferringParams]; // previously getInstallReferringParams
持久身份
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 is where we introduce the concept of an 'identity'.
要识别用户,只需调用:
// previously identifyUser:
Branch.getInstance().setIdentity(your user id) // your user id should not exceed 127 characters
// previously identifyUser:
[[Branch getInstance] setIdentity:your user id]; // your user id should not exceed 127 characters
参数
参数 | 描述 | 必要项 |
---|---|---|
identity (NSString *) | 这是您要在 Branch 系统中标记用户的别名。请注意,我们仅支持每个用户使用一个别名。 | Y |
注销
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.
警告
This call will clear the promo credits and attribution on the device.
Branch.getInstance().logout() // previously clearUser
[[Branch getInstance] logout]; // previously clearUser
追踪用户操作和事件
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.
有关应用 BranchEvents 的分析可在 Branch 操作后台 (Dashboard)找到,并且 BranchEvents 还提供与许多第三方分析提供商的紧密集成。
The BranchEvent
class can be simple to use. For example:
BranchEvent.standardEvent(.addToCart).logEvent()
[[Branch getInstance] logout]; // previously clearUser
For best results, use the Branch standard event names defined in BranchEvent.h
. But you can use your own custom event names too:
BranchEvent.customEventWithName("User_Scanned_Item").logEvent()
[[BranchEvent customEventWithName:@"User_Scanned_Item"] logEvent];
额外事件特定数据也可以通过事件进行追踪:
let event = BranchEvent.standardEvent(.purchase)
event.transactionID = "tx-12344555"
event.currency = .USD
event.revenue = 12.70
event.shipping = 10.20
event.tax = 2.50
event.coupon = "coupon_code"
event.affiliation = "store_affiliation"
event.eventDescription = "Shopper made a purchase."
event.searchQuery = "Fashion Scarf"
event.contentItems = [ branchUniversalObject ]
event.customData = [
"Item_Color": "Red",
"Item_Size": "Large"
]
event.logEvent()
BranchEvent *event = [BranchEvent standardEvent:BranchStandardEventPurchase];
event.transactionID = @"tx-12344555";
event.currency = BNCCurrencyUSD;
event.revenue = [NSDecimalNumber decimalNumberWithString:@"12.70"];
event.shipping = [NSDecimalNumber decimalNumberWithString:@"10.20"];
event.tax = [NSDecimalNumber decimalNumberWithString:@"2.50"];
event.coupon = @"coupon_code";
event.affiliation = @"store_affiliation";
event.eventDescription= @"Shopper made a purchase.";
event.searchQuery = @"Fashion Scarf";
event.contentItems = @[ branchUniversalObject ];
event.customData = (NSMutableDictionary*) @{
@"Item_Color": @"Red",
@"Item_Size": @"Large"
};
[event logEvent];
Apple Search Ads
Branch 可以通过在应用安装时从
Apple 获取搜索广告的归因来帮助追踪您的 Apple Search Ad campaign。然后,您可以使用在 Apple Search Ad 操作后台 (Dashboard)中设置的
参数,诸如 campaign 名称之类的参数,并在安装后在您的应用中采取特殊措施,或者仅在 Branch 操作后台 (Dashboard)
追踪 campaign 效果,以及其他 Branch
统计信息,例如总安装次数,推荐次数和 app link 统计信息。
- 外部资源
- 重要提示:您必须将 iAd.framework 添加到项目中才能启用 Apple Search Ad 检查。
- (void) delayInitToCheckForSearchAds
- (void) delayInitToCheckForSearchAds
请调用此方法,以便在 Branch 初始化之前启用 Apple Search Ads 检查。这个方法
必须在初始化 Branch 会话之前调用。
More information on this can be referenced in the Apple Search Ads docs.
Branch.getInstance().delayInitToCheckForSearchAds
[[Branch getInstance] delayInitToCheckForSearchAds];
启用或禁用用户追踪
为了符合追踪要求,您可以在 SDK 级别禁用追踪。您只需调用:
Branch.setTrackingDisabled(true)
[Branch setTrackingDisabled:YES];
这将防止发送任何 Branch 网络请求(深度链接除外)。如果有人点击 Branch Link,但又不想被追踪,我们会将深度链接数据返回给应用,但不会捕获任何追踪信息。
在 “do-not-track” 模式下,您仍然可以创建和分享链接。链接没有可识别的信息,且将是长格式链接。如果用户表示不想被追踪,则事件追踪不会将数据传回服务器。您可以随时通过调用上述函数来更改此行为。 trackingDisabled 状态已被保存并在应用运行期间持续存在。
Branch Universal Object(用于深度链接,内容分析和索引编制)
随着 iOS 中更多方法的演变,我们发现越来越难以管理所有这些方法。我们尽可能多地将其抽象化到一个 Branch Universal Object 概念。它与您要分享的事物(内容或用户)相关联。您可以设置与该对象关联的所有 metadata,然后调用操作方法以在 Spotlight 中获取链接或索引。
Branch Universal Object 最佳实践
这里有一组最佳实践,可确保您的分析正确无误,并且您的内容有效地在 Spotlight 上排名。
- 将
canonicalIdentifier
to a unique, de-duped value across instances of the app - 请确保
title
,contentDescription
andimageUrl
properly represent the object - Call
showShareSheet
andcreateShortLink
later in the life cycle, when the user takes an action that needs a link - 当采取相应的用户操作时,调用其他对象事件(购买,分享完成等)
- 将
contentIndexMode
toContentIndexModePublic
orContentIndexModePrivate
. If BranchUniversalObject is set toContentIndexModePublic
, then content would indexed usingNSUserActivity
, or else content would be index usingCSSearchableIndex
on Spotlight.
注意
Content indexed using
CSSearchableItem
could be removed from Spotlight but cannot be removed if indexed usingNSUserActivity
。
需要避免的实践:
- Don't set the same
title
,contentDescription
andimageUrl
across all objects. - 请不要等到用户分享再初始化对象并注册视图。
- 请不要等到您需要链接再初始化对象。
- Don't create many objects at once and register views in a
for
loop.
Branch Universal Object
方法和属性
let branchUniversalObject: BranchUniversalObject = BranchUniversalObject(canonicalIdentifier: "item/12345")
branchUniversalObject.title = "My Content Title"
branchUniversalObject.contentDescription = "My Content Description"
branchUniversalObject.imageUrl = "https://example.com/mycontent-12345.png"
branchUniversalObject.contentMetadata.contentSchema = .product;
branchUniversalObject.contentMetadata.customMetadata["property1"] = "blue"
branchUniversalObject.contentMetadata.customMetadata["property2"] = "red"
#import "BranchUniversalObject.h"
BranchUniversalObject *branchUniversalObject = [[BranchUniversalObject alloc] initWithCanonicalIdentifier:@"item/12345"];
branchUniversalObject.title = @"My Content Title";
branchUniversalObject.contentDescription = @"My Content Description";
branchUniversalObject.imageUrl = @"https://example.com/mycontent-12345.png";
branchUniversalObject.contentMetadata.contentSchema = BranchContentSchemaCommerceProduct;
branchUniversalObject.contentMetadata.customMetadata[@"property1"] = @"blue";
branchUniversalObject.contentMetadata.customMetadata[@"property2"] = @"red";
属性
属性 | 描述 |
---|---|
canonicalIdentifier | This is the unique identifier for content that will help Branch de-dupe across many instances of the same thing. If you have a website with pathing, feel free to use that. Or, if you have database identifiers for entities, use those. |
标题 | This is the name for the content and will automatically be used for the OG tags. It will insert $og_title into the data dictionary of any link created. |
contentDescription | This is the description for the content and will automatically be used for the OG tags. It will insert $og_description into the data dictionary of any link created. |
imageUrl | This is the image URL for the content and will automatically be used for the OG tags. It will insert $og_image_url into the data dictionary of any link created. |
关键字 | 描述对象的关键字。这些用于 Spotlight 搜索和 Web 抓取,以便用户可以找到您的内容。 |
locallyIndex | 如果设置为 true,则 Branch 将在用户手机的 Spotlight 上为该内容编制索引。 |
publiclyIndex | 如果设置为 true,则 Branch 将在 Google,Branch 等为该内容编制索引。 |
expirationDate | 内容将不再可用或有效的日期。目前,此功能仅用于 Spotlight 索引编制,但将来会被 Branch 使用。 |
contentMetadata | Details that further describe your content. Set the properties of this sub-object depending on the type of content that is relevant to your content. See the Metadata Property table below for further information. |
BranchUniversalObject.contentMetadata
The BranchUniversalObject.contentMetadata
properties further describe your content. These properties are trackable in the Branch dashboard and will be automatically exported to your connected third-party app intelligence partners like Adjust or Mixpanel.
Set the properties of this sub-object depending on the type of content that is relevant to your content. The BranchUniversalObject.contentMetadata.contentSchema
property describes the type of object content. Set other properties as is relevant to the type.
Metadata Property | 描述 |
---|---|
contentMetadata.contentSchema | Set this property to a BranchContentSchema enum that best describes the content type. It accepts values likeBranchContentSchemaCommerceProduct and BranchContentSchemaMediaImage 。 |
contentMetadata.customMetadata | 该词典包含您希望与 Branch Universal Object 相关的所有其他参数。用户点击链接并打开应用后,即可使用这些功能。 |
contentMetadata.price | 与以下 commerce 相关事件结合使用的商品价格。 |
contentMetadata.currency | The currency representing the price in ISO 4217 currency code. The default is USD. |
contentMetadata.quantity | 数量。 |
contentMetadata.sku | 供应商 SKU。 |
contentMetadata.productName | 产品名称。 |
contentMetadata.productBrand | 产品品牌。 |
contentMetadata.productCategory | The BNCProductCategory value, such as BNCProductCategoryAnimalSupplies or BNCProductCategoryFurniture 。 |
contentMetadata.productVariant | 产品变体。 |
contentMetadata.condition | The BranchCondition value, such as BranchConditionNew or BranchConditionRefurbished 。 |
ratingAverage, ratingCount, ratingMax | 内容的评分。 |
addressStreet, addressCity, addressRegion, addressCountry, addressPostalCode | 内容的地址。 |
latitude, longitude | 内容的经度和纬度。 |
imageCaptions | 内容图像的图像标题。 |
缩短链接
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.
编码说明
One quick note about encoding. Since NSJSONSerialization
supports a limited set of classes, we do some custom encoding to allow additional types. Current supported types include NSDictionary
, NSArray
, NSURL
, NSString
, NSNumber
, NSNull
, and NSDate
(encoded as an ISO8601 string with timezone). If a parameter is of an unknown type, it will be ignored.
let linkProperties: BranchLinkProperties = BranchLinkProperties()
linkProperties.feature = "sharing"
linkProperties.channel = "facebook"
linkProperties.addControlParam("$desktop_url", withValue: "http://example.com/home")
linkProperties.addControlParam("$ios_url", withValue: "http://example.com/ios")
branchUniversalObject.getShortUrl(with: linkProperties) { (url, error) in
if error == nil {
NSLog("got my Branch link to share: %@", url)
}
}
#import "BranchLinkProperties.h"
BranchLinkProperties *linkProperties = [[BranchLinkProperties alloc] init];
linkProperties.feature = @"sharing";
linkProperties.channel = @"facebook";
[linkProperties addControlParam:@"$desktop_url" withValue:@"http://example.com/home"];
[linkProperties addControlParam:@"$ios_url" withValue:@"http://example.com/ios"];
[branchUniversalObject getShortUrlWithLinkProperties:linkProperties andCallback:^(NSString *url, NSError *error) {
if (!error) {
NSLog(@"success getting url! %@", url);
}
}];
链接属性参数
参数 | 描述 |
---|---|
渠道 | 链接的渠道。示例可以为 Facebook,Twitter,短信等,具体取决于分享位置。 |
功能 | The feature the generated link will be associated with. Eg. sharing 。 |
alias | 链接的别名。例如, myapp.com/customalias |
matchDuration | 来自链接的点击归因窗口(以秒为单位)。 |
阶段 | 用于生成链接的阶段,指示用户位于漏斗的哪个部分。 |
标签 | 与链接相关的 tag string 数组。 |
controlParams | 建立 Branch Link 时要使用的字典。您可以在此处指定自定义行为控件,如下表所述。 |
您可以通过在字典插入以下可选 key 来进行自定义重定向:
Key | 值 |
---|---|
"$fallback_url" | 未安装应用时将所有平台的用户发送到这里。请注意,Branch 会将所有 robots 转发到此 URL,从而覆盖在链接中输入的所有 OG 标签。 |
"$desktop_url" | 在台式机或笔记本电脑上发送用户处。默认情况下,它是 Branch 托管的 text-me 服务。 |
"$android_url" | Play Store 的替代 URL,用于在用户没有该应用的情况下向其发送。只有当您想要移动网页启动时才需要它。 |
"$ios_url" | App Store 的替代 URL,用于在用户没有该应用的情况下向其发送。只有当您想要移动网页启动时才需要它。 |
"$ipad_url" | 与上述相同,但适用于 iPad Store。 |
"$fire_url" | 与上述相同,但适用于 Amazon Fire Store。 |
"$blackberry_url" | 与上述相同,但适用于 Blackberry Store。 |
"$windows_phone_url" | 与上述相同,但适用于 Windows Store。 |
"$after_click_url" | 当用户转到应用后返回浏览器时,将其带到该 URL。仅限 iOS; Android 版即将面世 。 |
通过在字典插入以下可选 key,您可以控制每个链接的直接深度链接:
Key | 值 |
---|---|
"$deeplink_path" | 您希望我们追加到您的 URI 的深度链接路径的值。例如,您可以指定 "$deeplink_path": "radio/station/456",然后我们将使用 URI "yourapp://radio/station/456?link_click_id=branch-identifier" 打开应用。这主要是为了支持旧版深度链接基础架构。 |
"$always_deeplink" | true 或 false。 (默认设置为不先进行深度链接)即使我们不确定用户是否已安装该应用,也可以指定此 key 以使我们的链接服务团队尝试打开该应用。如果未安装该应用,我们将退回到相应的 app store 或 $platform_url key。默认情况下,我们仅在看到用户通过 Branch Link 在您的应用中启动会话(已被 Branch cookie 并进行深度链接)时才会打开该应用。 |
获取简短 URL 参数
参数 | 描述 |
---|---|
linkProperties | 上面创建的链接属性,描述了您想要的链接类型 |
callback | 成功时使用 url 调用的回调,如果出现问题则返回错误。请注意,我们会以100%的概率返回链接。如果网络可用,则会是一个短链接;如果网络不可用,则会是一个长链接。 |
UIActivityView 分享表
UIActivityView is the standard way of allowing users to share content from your app. 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.
示例 UIActivityView 分享表

UIActivityView 分享表
Branch iOS SDK 在 UIActivityViewController 上包含一个包装器,该包装器将生成 Branch 短 URL,并使用用户选择的渠道(Facebook,Twitter 等)自动对其进行标签。请注意,某些渠道限制对某些字段的访问。例如,Facebook 禁止您预填充消息。
let linkProperties: BranchLinkProperties = BranchLinkProperties()
linkProperties.feature = "sharing"
linkProperties.addControlParam("$desktop_url", withValue: "http://example.com/home")
linkProperties.addControlParam("$ios_url", withValue: "http://example.com/ios")
branchUniversalObject.showShareSheet(with: linkProperties,
andShareText: "Super amazing thing I want to share!",
from: self) { (activityType, completed) in
NSLog("done showing share sheet!")
}
#import "BranchLinkProperties.h"
BranchLinkProperties *linkProperties = [[BranchLinkProperties alloc] init];
linkProperties.feature = @"sharing";
[linkProperties addControlParam:@"$desktop_url" withValue:@"http://example.com/home"];
[linkProperties addControlParam:@"$ios_url" withValue:@"http://example.com/ios"];
[branchUniversalObject showShareSheetWithLinkProperties:linkProperties
andShareText:@"Super amazing thing I want to share!"
fromViewController:self
completion:^(NSString *activityType, BOOL completed){
NSLog(@"finished presenting");
}];
显示分享表参数
参数 | 描述 |
---|---|
linkProperties | The feature the generated link will be associated with. |
andShareText | A dictionary to use while building up the Branch link. |
fromViewController | |
completion |
进一步自定化
大多数共享选项仅包含一串文本,但电子邮件除外,该电子邮件具有主题和正文。共享文本将填充在正文中,您可以在链接属性中指定电子邮件主题,如下所示。
linkProperties.addControlParam("$email_subject", withValue: "Therapists hate him.")
[linkProperties addControlParam:@"$email_subject" withValue:@"This one weird trick."];
您还可以选择将 HTML 添加到电子邮件选项中并自定义链接文本。如果省略了链接文本,则使用 url 本身
linkProperties.addControlParam("$email_html_header", withValue: "<style>your awesome CSS</style>\nOr Dear Friend,")
linkProperties.addControlParam("$email_html_footer", withValue: "Thanks!")
linkProperties.addControlParam("$email_html_link_text", withValue: "Tap here")
[linkProperties addControlParam:@"$email_html_header" withValue:@"<style>your awesome CSS</style>\nOr Dear Friend,"];
[linkProperties addControlParam:@"$email_html_footer" withValue:@"Thanks!"];
[linkProperties addControlParam:@"$email_html_link_text" withValue:@"Tap here"];
快速更改分享文本
You can change the link shareText and other link parameters based on the choice the user makes on the sharesheet activity. First, set the BranchShareLink
delegate with an object that follows the BranchShareLinkDelegate
protocol.
The optional - (void) branchShareLinkWillShare:
delegate method will be called just after the user selects a share action, like share by email for instance, and before the share action is shown to the user, like when the email composer is shown to the user with the share text. This is an ideal time to change the share text based on the user action.
The optional - (void) branchShareLink:didComplete:withError:
delegate method will be called after the user has completed the share action. The didComplete
boolean will be YES
if the user shared the item, and NO
if the user cancelled. The error
value will indicate any errors that may have occurred.
覆盖 branchShareLinkWillShare 函数以更改您的 shareText
class ViewController: UITableViewController, BranchShareLinkDelegate
func branchShareLinkWillShare(_ shareLink: BranchShareLink) {
// Link properties, such as alias or channel can be overridden here based on the users'
// choice stored in shareSheet.activityType.
shareLink.shareText =
"Shared through '\(shareLink.linkProperties.channel!)'\nfrom Branch's TestBed-Swift" +
"\nat \(self.dateFormatter().string(from: Date()))."
}
@interface ViewController () <BranchShareLinkDelegate>
- (void) branchShareLinkWillShare:(BranchShareLink*)shareLink {
// Link properties, such as alias or channel can be overridden here based on the users'
// choice stored in shareSheet.activityType.
shareLink.shareText = [NSString stringWithFormat:
@"Shared through '%@'\nfrom Branch's Branch-TestBed\nat %@.",
shareLink.linkProperties.channel,
[self.dateFormatter stringFromDate:[NSDate date]]];
}
在 Spotlight 上列出内容
如果您想在 Spotlight 本地索引和云索引中列出您的 Branch Universal Object,这就是您要调用的方法。您需要在每次页面加载时注册视图,因为这有助于您在搜索中的全球排名。
branchUniversalObject.automaticallyListOnSpotlight = true
branchUniversalObject.automaticallyListOnSpotlight = YES;
[branchUniversalObject userCompletedAction:BranchStandardEventViewItem];
参数
参数 | 描述 |
---|---|
callback | Will return the URL that was used to list the content in Spotlight if you'd like to store it for your own records. |
使用链接属性在 Spotlight 上列出内容
如果您想在 Spotlight 本地索引和云索引中列出带有链接属性的 Branch Universal Object,这就是您要调用的方法。您需要在每次页面加载时注册视图,因为这有助于您在搜索中的全球排名。
universalObject.listOnSpotlight(with: linkProperty) { (url, error) in
if (error == nil) {
print("Successfully indexed on spotlight")
}
}
[universalObject listOnSpotlightWithLinkProperties:linkProperties callback:^(NSString * _Nullable url, NSError * _Nullable error) {
if (!error) {
NSLog(@"Successfully indexed on spotlight");
}
}];
参数
参数 | 描述 |
---|---|
callback | Will return the URL that was used to list the content in Spotlight if you'd like to store it for your own records. |
使用 CSSearchableIndex 在 Spotlight 上列出多个Branch Universal Object
在 Branch 分享实例上调用此方法以在 Spotlight 中列出多个 Branch Universal Object:
Branch.getInstance().indexOnSpotlight(usingSearchableItems: universalObjects,
completion: { (universalObjects, error) in
if (error) {
// Successfully able to index all the BUO on spotloght
}
})
[[Branch getInstance] indexOnSpotlightUsingSearchableItems:universalObjects
completion:^(NSArray<BranchUniversalObject *> *universalObjects,
NSError *error) {
if (!error) {
// Successfully able to index all the BUO on spotloght
}
}];
参数
参数 | 描述 |
---|---|
universalObjects | An array of all the Branch Universal Object that would indexed using CSSearchableIdex |
completion | Will return Branch Universal Object with dynamic urls as Spotlight identifier when indexing completes. |
如果已私有索引,则从 Spotlight 中删除 Branch Universal Object
私有索引的 Branch Universal Object 可从 Spotlight 中删除
universalObject.removeFromSpotlight { (error) in
if(error == nil) {
print("BUO successfully removed")
}
}
[universalObject removeFromSpotlightWithCallback:^(NSError * _Nullable error) {
if (!error) {
NSLog(@"universal Object removed from spotlight");
}
}];
参数
参数 | 描述 |
---|---|
Callback | Will return once Branch Universal Object is removed from spotlight. If spotlight is removed, the spotlightIdentifier variable of Branch Universal Object would be nil. |
如果已私有索引,则从 Spotlight 中删除多个 Branch Universal Object
私有索引的多个 Branch Universal Object 可从 Spotlight 中删除
Branch.getInstance().removeSearchableItems(with: [BUO1,BUO2]) { (error) in
if (error == nil) {
print("An array of BUOs removed from spotlight")
}
}
[[Branch getInstance] removeSearchableItemsWithBranchUniversalObjects:@[BUO1,BUO2] callback:^(NSError *error) {
if (!error) {
NSLog(@"An array of BUOs removed from spotlight");
}
}]
参数
参数 | 描述 |
---|---|
Callback | Will return once all Branch Universal Object is removed from spotlight. If spotlight is removed, the spotlightIdentifier variable of all Branch Universal Object would be nil. |
如果已私有索引,则从 Spotlight 中删除所有 Branch Universal Object
私有索引的所有 Branch Universal Object 可从 Spotlight 中删除
Branch.getInstance().removeAllPrivateContentFromSpotLight { (error) in
if (error == nil) {
print("All branch privately indexed content removed from spotlight")
}
}
[[Branch getInstance] removeAllPrivateContentFromSpotLightWithCallback:^(NSError *error) {
if (!error) {
NSLog(@"All branch privately indexed content removed from spotlight");
}
}];
参数
参数 | 描述 |
---|---|
Callback | Will return once all Branch Universal Object is removed from spotlight. Note: SpotlightIdentifer would not be nil of all the Branch Universal Object been removed from spotlight as Branch SDK doesn't cache the Branch Universal Objects. |
Updated 4 months ago