Button Developers

iOS App Setup

The Button Merchant Library for iOS is a lightweight, open-source library designed to manage the Button Attribution Token. By the end of this section, you’ll be able to associate all incoming users against their subsequent taps in other applications that brought them to your iOS application.

Add the Merchant Library

Include Dependency

To get started, add the Button Merchant Library through CocoaPods, Carthage or Swift Package Manager.

In Xcode, navigate to **File → Swift Packages → Add Package Dependency**

https://github.com/button/button-merchant-ios
pod 'ButtonMerchant', '~> 1'
dependencies: [
    .package(url: "https://github.com/button/button-merchant-ios", .upToNextMajor(from: "1.4.1"))
]
github "button/button-merchant-ios" ~> 1.4

👍

Allow auto-updating

The Button Merchant Library is strictly semantically versioned so we strongly recommend allowing automatic updates up to the next major version.

Before continuing run pod install, carthage build or allow Swift Package Manager to include the Button Merchant Library, depending on your method of inclusion.

Setup Library

In your AppDelegate file, import ButtonMerchant and initialize it by calling the ButtonMerchant.configure method passing your iOS Application ID registered in the Button Dashboard.

Additionally, some users will be initializing your application from a fresh install after following a promotion. In order to fulfill these specific user requests, include a call to the ButtonMerchant.handlePostInstallURL method. This will fetch the user’s intent prior to the fresh install, and allow you to route them directly to your relevant promotion. For more information on the handlePostInstallURL method, take a look at Button Deferred Deep Linking.

import ButtonMerchant
    
func application(_ application: UIApplication, didFinishLaunchingWithOptions 
                 launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  // Replace app-xxxxxxxxxxxxxxxx with your App ID from the 
  // Button Dashboard https://app.usebutton.com
  ButtonMerchant.configure(applicationId: "<#app-xxxxxxxxxxxxxxxx#>")

  ButtonMerchant.handlePostInstallURL { url, error in

                                       guard let url = url else {
                                         // Use the information in this url to direct 
                                         // the user to the correct destination in your app.
                                       }
                                      }

  return true
}
@import ButtonMerchant; 

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Replace app-xxxxxxxxxxxxxxxx with your App ID from the Button Dashboard https://app.usebutton.com
    [ButtonMerchant configureWithApplicationId:@"<#app-xxxxxxxxxxxxxxxx#>"];

    [ButtonMerchant handlePostInstallURL:^(NSURL * _Nullable url, NSError * _Nullable error) {
      if (url) {
        // Route user to the url
      }
    }];

    return YES;
  }

📘

Note

The Button Merchant Library is disabled by default. No user activity is reported and no data is collected until configured with an application id. Initialization can be deferred by simply not calling this method until ready to do so.

Register Deep Links

Button’s Merchant Library will abstract any complexities of token management for you, including extracting the token from any incoming deeplinks.

For users that have already installed your application and are entering from another application’s promotion, Button’s Merchant library will help you source where they came from. Pass the incoming URL to the Button Merchant Library in order to accurately attribute and handle their intent.

The ButtonMerchant class allows you to handle both Universal Linking by passing incoming user activity to trackIncomingUserActivity, and Custom Scheme URLs by passing incoming URLs to trackIncomingURL.

🚧

Note

If you are using scene delegates, incoming URLs will arrive in your SceneDelegate (i.e. UIWindowSceneDelegate) instead of your UIApplicationDelegate.

// Handle custom scheme urls
func application(_ app: UIApplication, open url: URL, 
                 options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
    
    ButtonMerchant.trackIncomingURL(url)
    
    // Your normal deep link route handling to show the user the content
    
    return true
}
    
// Handle Universal Links
func application(_ application: UIApplication, continue 
                 userActivity: NSUserActivity, 
                 restorationHandler: @escaping ([Any]?) -> Void) -> Bool {

  ButtonMerchant.trackIncomingUserActivity(userActivity)

   // Your normal deep link route handling to show the user the content

  return true
}
// Handle when the app is launched by a deeplink:
func scene(_ scene: UIScene, willConnectTo 
           session: UISceneSession, 
           options connectionOptions: UIScene.ConnectionOptions) {

  // Handle custom scheme urls
  if let url = connectionOptions.urlContexts.first?.url {
    ButtonMerchant.trackIncomingURL(url)
  }

  // Handle Universal Links
  if let url = connectionOptions.userActivities.first?.webpageURL {
    ButtonMerchant.trackIncomingUserActivity(userActivity)
  }
}

// Handle incoming deeplinks when the app is already running:

// Handle custom scheme urls
func scene(_ scene: UIScene, openURLContexts 
           URLContexts: Set<UIOpenURLContext>) {
  guard let url = URLContexts.first?.url else { return }
  ButtonMerchant.trackIncomingURL(url)
}

// Handle Universal Links
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
  ButtonMerchant.trackIncomingUserActivity(userActivity)
}
// Handle custom scheme urls
- (BOOL)application:(UIApplication *)app 
      openURL:(NSURL *)url
    options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

        [ButtonMerchant trackIncomingURL:url];

        return YES;
}

// Handle Universal Links
- (BOOL)application:(UIApplication *)application
  continueUserActivity:(NSUserActivity *)userActivity
    restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler {

        [ButtonMerchant trackIncomingUserActivity:userActivity];

        return YES;
}

Setup your Button Links domain

Xcode Entitlement

Button uses Universal Links to open your app from the Button Links domain.

If you have't already, enable the Associated Domains Capability and then add the following line to the list of domains.

applinks:yourdomain.bttn.io

📘

Note

Replacing yourdomain.bttn.io with your Button Links domain

Button Dashboard Configuration

🚧

Note

This step assumes you have completed Reserve your Link URL

Lastly, you’ll need to configure your App Site Association file and add your team identifier to the Button Dashboard.

  • Navigate to the Button Dashboard Apps Section
  • Choose your iOS app and click it's name to drill in.
  • Scroll down to the Configurations section and select Add Manual Configuration. If you've already added one, click Edit on the right side of that record.
<team_identifier>.com.example.app
  • Populate the Bundle Identifier including the Team Identifier as noted above.

Report Button Attribution Token

Once the user has placed an order in your app, include the Button Attribution Token before sending the user’s checkout request to your checkout API. The Button Attribution Token can be retrieved by calling the attributionToken method from the Button Merchant Library.

Let’s say your user has successfully made a purchase for a pair of jeans on your client application. Before sending that purchase request to your checkout API, retrieve the Button Attribution Token using ButtonMerchant.attributionToken

// Obtain Attribution Token
if let token = ButtonMerchant.attributionToken {
    // referred token is present - add to order
}
NSString *token = ButtonMerchant.attributionToken;
if (token) {
  // referred token is present - add to order
}

Once the Button Attribution Token has been retrieved, include it when sending the user’s order request to your checkout API.

// Set parameters for POST, including Attribution Token
let parameters: Parameters = [
  "token": token, // Attribution Token from previous section
  "price": 50.00,
  "location": "New York",
  "items": "Jeans"
]

// Perform POST request to your Checkout API (server)
Alamofire.request("checkout-api.yourbrand.com", method: .post, parameters: parameters, encoding: JSONEncoding(options: []))
NSDictionary *params = @{ @"token": token, // Attribution token above
                         @"price": @50.00,
                         @"location": @"New York",
                         @"items": @"Jeans" };

// Perform POST request to your Checkout API (server)
[AFHTTPSessionManager.manager POST:@"checkout-api.yourbrand.com"
                               parameters:params
                               progress:nil
                               success:successHandler 
                               failure:errorHandler];

Report User Activity

You can report intermediate steps in the checkout funnel for analytics and measurement purposes including:

  • Product Views
  • Add To Cart
  • Cart Views

This is achieved by first creating a Product, and then reporting it to the Merchant Library.

/// Create product item
let product = ButtonProduct()
product.id = "abc123"
product.upc = "012345678901"
product.categories = ["Electronics", "Televisions"]
product.name = "Flatscreen TV"
product.currency = "USD"
product.value = 39999
product.quantity = 1
product.url = "https://yourbrand.com/p/tv123"
product.attributes = ["size": "40 inch"]

/// Report a product view
ButtonMerchant.activity.productViewed(product)

/// Report a product added to the cart
ButtonMerchant.activity.productAddedToCart(product)

/// Report a cart view
ButtonMerchant.activity.cartViewed([product, otherProduct])
/// Create product item
ButtonProduct *product = [[ButtonProduct alloc] init];
product.id = @"abc123";
product.upc = @"012345678901";
product.categories = @[@"Electronics", @"Televisions"];
product.name = @"Flatscreen TV";
product.currency = @"USD";
product.value = @39999;
product.quantity = @1;
product.url = @"https://yourbrand.com/p/tv123";
product.attributes = @{@"size": @"40 inch"};

/// Report a product view
[[ButtonMerchant activity] productViewed:product];

/// Report a product added to the cart
[[ButtonMerchant activity] productAddedToCart:product];

/// Report a cart view
[[ButtonMerchant activity] cartViewed:@[product, otherProduct]];

Note: You can pass your own product object by implementing the protocol ButtonProductCompatible on your product class.

This concludes handling a user journey from outside applications.

Updated 21 days ago



iOS App Setup


The Button Merchant Library for iOS is a lightweight, open-source library designed to manage the Button Attribution Token. By the end of this section, you’ll be able to associate all incoming users against their subsequent taps in other applications that brought them to your iOS application.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.