macOS Advanced Features

Turning on Logging

To help debugging your app, you can turn on Branch logging, which logs to the console. Remember to turn it off in your production app.



Setting User 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 'user identity'.


private func login(userIdentity: String?) {
        guard let userIdentity = userIdentity else { return }

                                              completion: { (branchSession, error) in
                                                // Do stuff with login
[Branch setUserIdentity:completion:]

See setUserIdentity:completion:

Get User Identity

Use the getUserIdentity method to retrieve the user ID set via setUserIdentity.


var userIdentity = Branch.sharedInstance().getUserIdentity()
NSString *userIdentity = [Branch sharedInstance].getUserIdentity();

See getUserIdentity


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 attribution on the device.


private func logout() {
        Branch.sharedInstance.logout(completion: { (error) in
          // Do stuff on logout
[Branch logoutWithCompletion:]

See logoutWithCompletion:

Tracking User Actions and Events

Use the BranchEvent class 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.

The BranchEvent class can be simple to use. For example:

[[Branch sharedInstance]
    logEvent:[BranchEvent standardEvent:BranchStandardEventAddToCart]];

For best results use the Branch standard event names defined in BranchEvent.h. But you can use your own custom event names too:

Branch.sharedInstance.logEvent(.customEvent(withName: "User_Scanned_Item"))
[[Branch sharedInstance]
    logEvent:[BranchEvent customEventWithName:@"User_Scanned_Item"]];

Extra event specific data can be tracked with the event as well:

let event = BranchEvent.standardEvent(.purchase)
event.transactionID    = "tx-12344555"
event.currency         = .USD
event.revenue          = 12.70
event.shipping         = 10.20              = 2.50           = "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"
BranchEvent *event    = [BranchEvent standardEvent:BranchStandardEventPurchase];
event.transactionID   = @"tx-12344555";
event.currency        = BNCCurrencyUSD;
event.revenue         = [NSDecimalNumber decimalNumberWithString:@"12.70"];
event.shipping        = [NSDecimalNumber decimalNumberWithString:@"10.20"];             = [NSDecimalNumber decimalNumberWithString:@"2.50"];          = @"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"
[[Branch sharedInstance] logEvent: event];

Enable or Disable User Tracking

If you need to comply with a user's request to not be tracked for GDPR purposes, or otherwise determine that a user should not be tracked, utilize this field to prevent Branch from sending network requests. This setting can also be enabled across all users for a particular link, or across your Branch links.

Branch.sharedInstance().trackingDisabled = true
[Branch sharedInstance].trackingDisabled = YES;

You can choose to call this throughout the lifecycle of the app. Once called, network requests will not be sent from the SDKs. Link generation will continue to work, but will not contain identifying information about the user. In addition, deep linking will continue to work, but will not track analytics for the user.

Set Initialization Metadata


Data Integration Only

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:

let dict = NSMutableDictionary()
        dict.setObject("your metadata" as NSString, forKey: "sample_key" as NSString)
        Branch.sharedInstance.requestMetadataDictionary = dict
NSMutableDictionary<NSString *, NSString *> *metadata = [NSMutableDictionary<NSString *, NSString *> new];
    [metadata setObject:@"your metadata" forKey:@"sample_key"];
    [[Branch sharedInstance] setRequestMetadataDictionary:metadata];

Branch Universal Object

Use a BranchUniversalObject to describe content in your app for deep links, content analytics and indexing.

The properties object describes your content in a standard way so that it can be deep linked, shared, or indexed on spotlight
for instance. You can set all the properties associated with the object and then call action methods on it to create a link or index
the content on Spotlight.

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 imageUrl properly represent the object
  3. Call showShareSheet and createShortLink later in the life cycle, when the user takes an action that needs a link
  4. Call the additional object events (purchase, share completed, etc) when the corresponding user action is taken
  5. Set the contentIndexMode to ContentIndexModePublic or ContentIndexModePrivate. If BranchUniversalObject is set to ContentIndexModePublic, then content would indexed using NSUserActivity, or else content would be index using CSSearchableIndex on Spotlight.



Content indexed using CSSearchableItem could be removed from Spotlight but cannot be removed if indexed using NSUserActivity.


Practices to Avoid

  1. Don't set the same title, contentDescription and imageUrl 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 for loop.


let branchUniversalObject: BranchUniversalObject = BranchUniversalObject(canonicalIdentifier: "item/12345")
branchUniversalObject.title = "My Content Title"
branchUniversalObject.contentDescription = "My Content Description"
branchUniversalObject.imageUrl = ""
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 = @"";
branchUniversalObject.contentMetadata.contentSchema = BranchContentSchemaCommerceProduct;
branchUniversalObject.contentMetadata.customMetadata[@"property1"] = @"blue";
branchUniversalObject.contentMetadata.customMetadata[@"property2"] = @"red";


canonicalIdentifierThis 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.
titleThis 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.
contentDescriptionThis 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.
imageUrlThis 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.
keywordsKey words that describe the object. These are used for Spotlight search and web scraping so that users can find your content.
locallyIndexIf set to true, Branch will index this content on Spotlight on the user's mac.
publiclyIndexIf set to true, Branch will index this content on Google, Branch, etc.
expirationDateThe date when the content will not longer be available or valid. Currently, this is only used for Spotlight indexing but will be used by Branch in the future.
contentMetadataDetails 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 table below 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.

contentMetadata.contentSchemaSet this property to a BranchContentSchema enum that best describes the content type. It accepts values like BranchContentSchemaCommerceProduct and BranchContentSchemaMediaImage.
contentMetadata.customMetadataThis dictionary contains any extra parameters you'd like to associate with the Branch Universal Object. These will be made available to you after the user clicks the link and opens up the app.
contentMetadata.priceThe price of the item to be used in conjunction with the commerce related events below.
contentMetadata.currencyThe currency representing the price in ISO 4217 currency code. The default is USD.
contentMetadata.quantityThe quantity.
contentMetadata.skuThe vendor SKU.
contentMetadata.productNameProduct name.
contentMetadata.productBrandProduct brand.
contentMetadata.productCategoryThe BNCProductCategory value, such as BNCProductCategoryAnimalSupplies or BNCProductCategoryFurniture.
contentMetadata.productVariantThe product variant.
contentMetadata.conditionThe BranchCondition value, such as BranchConditionNew or BranchConditionRefurbished.
ratingAverage, ratingCount, ratingMaxThe rating for your content.
addressStreet, addressCity, addressRegion, addressCountry, addressPostalCodeThe address of your content.
latitude, longitudeThe longitude and latitude of your content.
imageCaptionsImage captions for the content's images.

Tracking User Actions and Events

We've added a series of custom events that you'll want to start tracking for rich analytics and targeting. Here's a list below with a sample snippet that calls the register view event.

BranchStandardEventViewItemUser viewed the object
BranchStandardEventAddToWishlistUser added the object to their wishlist
BranchStandardEventAddToCartUser added object to cart
BranchStandardEventInitiatePurchaseUser started to check out
BranchStandardEventPurchaseUser purchased the item
BranchStandardEventShareUser completed a share


[branchUniversalObject userCompletedAction:BranchStandardEventViewItem];





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.


Encoding Note

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" = "facebook"
linkProperties.addControlParam("$desktop_url", withValue: "")
linkProperties.addControlParam("$ios_url", withValue: "")

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"; = @"facebook";
[linkProperties addControlParam:@"$desktop_url" withValue:@""];
[linkProperties addControlParam:@"$ios_url" withValue:@""];

[branchUniversalObject getShortUrlWithLinkProperties:linkProperties andCallback:^(NSString *url, NSError *error) {
    if (!error) {
        NSLog(@"success getting url! %@", url);

Link Properties Parameters

channelThe channel for the link. Examples could be Facebook, Twitter, SMS, etc., depending on where it will be shared.
featureThe feature the generated link will be associated with, e.g., sharing.
controlParamsA dictionary to use while building up the Branch link. Here is where you specify custom behavior controls as described in the table below.

You can do custom redirection by inserting the following optional keys in the dictionary:

$fallback_urlWhere to send the user for all platforms when app is not installed. Note that Branch will forward all robots to this URL, overriding any OG tags entered in the link.
$desktop_urlWhere to send the user on a desktop or laptop. By default it is the Branch-hosted text-me service.
$android_urlThe replacement URL for the Play Store to send the user if they don't have the app. Only necessary if you want a mobile web splash.
$ios_urlThe replacement URL for the App Store to send the user if they don't have the app. Only necessary if you want a mobile web splash.
$ipad_urlSame as above, but for iPad Store.
$fire_urlSame as above, but for Amazon Fire Store.
$blackberry_urlSame as above, but for Blackberry Store.
$windows_phone_urlSame as above, but for Windows Store.
$after_click_urlWhen a user returns to the browser after going to the app, take them to this URL. iOS only; Android coming soon.
$afterclick_desktop_urlWhen a user on desktop returns to the desktop browser after going to the desktop app, take them to this URL.

You have the ability to control the direct deep linking of each link by inserting the following optional keys in the dictionary:

$deeplink_pathThe value of the deep link path that you'd like us to append to your URI. For example, you could specify "$deeplink_path": "radio/station/456" and we'll open the app with the URI "yourapp://radio/station/456?link_click_id=branch-identifier". This is primarily for supporting legacy deep linking infrastructure.
$always_deeplinktrue or false. (default is not to deep link first) This key can be specified to have our linking service force try to open the app, even if we're not sure the user has the app installed. If the app is not installed, we fall back to the respective app store or $platform_url key. By default, we only open the app if we've seen a user initiate a session in your app from a Branch link (has been cookied and deep linked by Branch).
aliasThe alias for a link, e.g.,
matchDurationThe attribution window in seconds for clicks coming from this link.
stageThe stage used for the generated link, indicating what part of a funnel the user is in.
tagsAn array of tag strings to be associated with the link.

Get Short Url Parameters

linkPropertiesThe link properties created above that describe the type of link you'd like
linkPropertiesThe callback that is called with url on success, or an error if something went wrong. Note that we'll return a link 100% of the time. Either a short one if network was available or a long one if it was not.

Create QR Code

  • Create a BranchUniversalObject and BranchLinkProperties
  • Create a BranchQRCode object and set the properties
  • Use getQRCodeAsImage() or getQRCodeAsData() to create a QR code
BranchLinkProperties *linkProperties = [BranchLinkProperties new];
    BranchUniversalObject *buo = [BranchUniversalObject new];
    BranchQRCode *qrCode = [BranchQRCode new];
    qrCode.codeColor = [NSColor colorWithCalibratedRed:0.1 green:0.8392 blue:1.0 alpha:1.0f];
    qrCode.backgroundColor = NSColor.whiteColor;
    qrCode.width = @500;
    qrCode.margin = @1;
    qrCode.centerLogo = @"";
    qrCode.imageFormat = BranchQRCodeImageFormatPNG;
    [qrCode getQRCodeAsImage:buo linkProperties:linkProperties completion:^(CIImage * _Nullable qrCodeImage, NSError * _Nullable error) {
        //Use the QR code image here...