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.

Property

Branch.loggingIsEnabled
Branch.loggingEnabled

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'.

Method

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

        Branch.sharedInstance.setUserIdentity(userIdentity,
                                              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.

Method

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

See getUserIdentity

Logout

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.

🚧

Warning

This call will clear attribution on the device.

Method

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(.standardEvent(.addToCart))
[[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
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"
]
Branch.sharedInstance.logEvent(event)
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"
};
[[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.

📘

Note

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.

Methods

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";

Properties

Property

Description

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.

title

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.

keywords

Key words that describe the object. These are used for Spotlight search and web scraping so that users can find your content.

locallyIndex

If set to true, Branch will index this content on Spotlight on the user's mac.

publiclyIndex

If set to true, Branch will index this content on Google, Branch, etc.

expirationDate

The 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.

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 table below BranchUniversalObject.contentMetadata

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.

Property

Description

contentMetadata.contentSchema

Set this property to a BranchContentSchema enum that best describes the content type. It accepts values like BranchContentSchemaCommerceProduct and BranchContentSchemaMediaImage.

contentMetadata.customMetadata

This 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.price

The price of the item to be used in conjunction with the commerce related events below.

contentMetadata.currency

The currency representing the price in ISO 4217 currency code. The default is USD.

contentMetadata.quantity

The quantity.

contentMetadata.sku

The vendor SKU.

contentMetadata.productName

Product name.

contentMetadata.productBrand

Product brand.

contentMetadata.productCategory

The BNCProductCategory value, such as BNCProductCategoryAnimalSupplies or BNCProductCategoryFurniture.

contentMetadata.productVariant

The product variant.

contentMetadata.condition

The BranchCondition value, such as BranchConditionNew or BranchConditionRefurbished.

ratingAverage, ratingCount, ratingMax

The rating for your content.

addressStreet, addressCity, addressRegion, addressCountry, addressPostalCode

The address of your content.

latitude, longitude

The longitude and latitude of your content.

imageCaptions

Image 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.

Event

Description

BranchStandardEventViewItem

User viewed the object

BranchStandardEventAddToWishlist

User added the object to their wishlist

BranchStandardEventAddToCart

User added object to cart

BranchStandardEventInitiatePurchase

User started to check out

BranchStandardEventPurchase

User purchased the item

BranchStandardEventShare

User completed a share

Methods

branchUniversalObject.logEvent(BranchStandardEventViewItem)
[branchUniversalObject userCompletedAction:BranchStandardEventViewItem];

Parameters

None

Returns

None

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.

Methods

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);
    }
}];

Link Properties Parameters

Parameter

Description

channel

The channel for the link. Examples could be Facebook, Twitter, SMS, etc., depending on where it will be shared.

feature

The feature the generated link will be associated with, e.g., sharing.

controlParams

A 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:

Key

Value

$fallback_url

Where 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_url

Where to send the user on a desktop or laptop. By default it is the Branch-hosted text-me service.

$android_url

The 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_url

The 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_url

Same as above, but for iPad Store.

$fire_url

Same as above, but for Amazon Fire Store.

$blackberry_url

Same as above, but for Blackberry Store.

$windows_phone_url

Same as above, but for Windows Store.

$after_click_url

When a user returns to the browser after going to the app, take them to this URL. iOS only; Android coming soon.

$afterclick_desktop_url

When 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:

Key

Value

$deeplink_path

The 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_deeplink

true 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).

alias

The alias for a link, e.g., myapp.com/customalias

matchDuration

The attribution window in seconds for clicks coming from this link.

stage

The stage used for the generated link, indicating what part of a funnel the user is in.

tags

An array of tag strings to be associated with the link.

Get Short Url Parameters

Parameter

Description

linkProperties

The link properties created above that describe the type of link you'd like

linkProperties

The 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 = @"https://cdn.branch.io/branch-assets/1598575682753-og_image.png";
    qrCode.imageFormat = BranchQRCodeImageFormatPNG;
    
    [qrCode getQRCodeAsImage:buo linkProperties:linkProperties completion:^(CIImage * _Nullable qrCodeImage, NSError * _Nullable error) {
        //Use the QR code image here...
    }];

Did this page help you?