iOS SDK

You can integrate the Outbound iOS SDK in your iOS app to send user and event data to Outbound from the user's device. You can also use it to manage push notification tokens and perform other tasks.

This document covers the following topics:

Add the Outbound SDK to Objective-C projects

Install the SDK

The Outbound SDK supports CocoaPods. Add the following to your Podfile:

pod 'Outbound'

Next run:

pod install
Include the SDK in your project

Merge the following code into your AppDelegate.m file:

#import "AppDelegate.h"
#import <Outbound/Outbound.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Outbound will ask for push notification permissions when the app
    // is launched, or when the user does a particular event, or
    // never, based on your configuration in the Outbound account.
    [Outbound initWithPrivateKey:@"PRIVATE_KEY"];
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // The user gave push notification permissions, store the APNS
    // token with the Outbound servers.
    [Outbound registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    if ([Outbound isUninstallTracker:userInfo]) {
        completionHandler(UIBackgroundFetchResultNewData);
    } else {
        // HANDLE YOUR BACKGROUND PUSH NOTIFICATIONS HERE
        completionHandler(UIBackgroundFetchResultNewData);
    }
}

Find and replace the PRIVATE_KEY placeholder in the didFinishLaunchingWithOptions application method. For more information on the private key, see Authentication in the introduction.

Add the Outbound SDK to Swift projects

Install the SDK

The Outbound SDK supports CocoaPods. For installation instructions, see Getting started on the CocoaPods website.

If not already done, create a Podfile for your project as follows:

  1. In Terminal, navigate to the top-level folder of your project (the one with the xcodeproj file).

  2. Create a Podfile with the following command:

    $ pod init

  3. Open the file in Xcode with the following command:

    $ open -a Xcode Podfile

    Depending on your version of CocoaPods, the default Podfile content should look as follows:

    # Uncomment the next line to define a global platform for your project
    # platform :ios, '9.0'
    
    target 'MyProject' do
      # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
      use_frameworks!
    
      # Pods for MyProject
    
    end
    
  4. Replace the # Pods for MyProject placeholder with the following line:

    pod 'Outbound'
    
  5. Save the Podfile and run the following command in Terminal:

    $ pod install
    

    Wait for CocoaPods to finish downloading and installing the Outbound SDK in your project.

  6. Close Xcode and relaunch it by double-clicking the .xcworkspace file that Cocoapods created in the top-level folder of your project.

    Because your project now contains a dependency managed by CocoaPods, from now on you must open the project with the .xcworkspace file, not .xcodeproj.

Update your Swift project to work with the Objective-C SDK

The Outbound SDK is written in Objective-C. This section shows you how to create a Swift bridging header to allow your Swift classes to communicate with the Objective-C classes.

  1. In Xcode, select File > New > File, then select Header File in the Source category and click Next.

  2. Name your file MyProject-Bridging-Header.h, replacing the MyProject placeholder with your project name.

  3. Create the file.

  4. Add the following lines to the header to import your Objective-C classes:

    #import <Foundation/Foundation.h>
    #import <Outbound/Outbound.h>
    

    Note: You can delete or comment out everything else in the default template.

  5. In the Navigator, click the top-most icon for your project (a blue file icon) to open your project settings.

  6. Open the Build Settings tab and make sure the All button is selected to show all settings.

  7. Scroll down to the Swift Compiler - General section and set the Objective-C Bridging Header value to the path of the header file you created above. Example:

    FoodTracker/FoodTracker-Bridging-Header.h

  8. Still on the settings page, scroll up to the Search Paths section and set the User Header Search Paths value to Pods.

    This is required so the import statement in your bridging header file can find the Outbound.h header file in the Pods directory.

Include the SDK in your project
  1. In Navigator, select your AppDelegate.swift file and add the following statement to the didFinishLaunchingWithOptions application function (in bold):

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Outbound will ask for push notification permissions when the app
        // is launched, or when the user does a particular event, or
        // never, based on your configuration in the Outbound account
        Outbound.initWithPrivateKey("PRIVATE_KEY")
        return true
    }

  2. Replace the PRIVATE_KEY placeholder with your own key.

    For more information on the private key, see Authentication in the introduction.

  3. Add the following application functions to the delegate file:

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // The user gave push notification permissions, store the APNS
        // token with the Outbound servers.
        Outbound.registerDeviceToken(deviceToken)
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (_: UIBackgroundFetchResult) -> Void) {
        if (Outbound.isUninstallTracker(userInfo)) {
            completionHandler(.newData);
        } else {
            // HANDLE YOUR BACKGROUND PUSH NOTIFICATIONS HERE
            completionHandler(.newData);
        }
    }
    

The updated AppDelegate.swift file should look like the following, without your own app's modifications:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        // Outbound will ask for push notification permissions when the app
        // is launched, or when the user does a particular event, or
        // never, based on your configuration in the Outbund account.
        Outbound.initWithPrivateKey("d19c97d82c6463265d9e9fb74a46d53")
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // The user gave push notification permissions, store the APNS
        // token with the Outbound servers.
        Outbound.registerDeviceToken(deviceToken)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (_: UIBackgroundFetchResult) -> Void) {
        if (Outbound.isUninstallTracker(userInfo)) {
            completionHandler(.newData);
        } else {
            // HANDLE YOUR BACKGROUND PUSH NOTIFICATIONS HERE
            completionHandler(.newData);
        }
    }

    ...
}

Identify a user

Use the identifyUserWithId method to send user data to Outbound. The method takes the following arguments:

  • a string containing the user id
  • attributes - a dictionary containing the user attributes
Example

Objective-C

// 1. (Optional) Define the custom attributes for the user.
NSMutableDictionary *customAttrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                    @"San Francisco", @"city",
                                    @"spicy", @"taste_preference", nil];

// 2. (Optional) Create the user object
NSMutableDictionary *user = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                             @"John", @"first_name",
                             @"Smith", @"last_name",
                             @"john@smith.com", @"email",
                             @"5555555555", @"phone_number",
                             customAttrs, @"attributes", nil];

// 3. Identify the user -- only the user id is required.
[Outbound identifyUserWithId:userId attributes:user];

Swift

// 1. (Optional) Define custom user attributes in a dictionary
var customAttrs: [AnyHashable: Any] = [
        "city": "San Francisco",
        "taste_preference": "spicy"
    ]

// 2. (Optional) Define user attributes in a dictionary
var user: [AnyHashable: Any] = [
        "first_name": "Jane",
        "last_name": "Doe",
        "email": "jdoe@example.com",
        "phone_number": "555-123-4567",
        "attributes": customAttrs
    ]

// 3. Identify the user (only the user id is required)
var userId = "4512345"
Outbound.identifyUser(withId: userId, attributes: user)

For more information about the user attributes, see Users.

Track an event

Use the trackEvent method to send event data to Outbound. The method takes the following arguments:

  • a string containing the event name
  • (optional) custom event properties. See Properties attribute in the Events documentation

You don't have to specify a user id. Outbound matches the device with a user.

Examples

Objective-C

[Outbound trackEvent:@"eventNameGoesHere" withProperties:@{@"foo": @"bar"}];

Swift

Outbound.trackEvent("eventNameGoesHere", withProperties: ["foo": "bar"])

For more information, see Events.

Assign a user to a group

You can assign users who share certain attributes to a group. This allows your company to create Outbound campaigns that target particular groups.

Use the identifyGroupWithId method to associate a user with a group. The method takes the following arguments:

  • a string that specifies the group name
  • userId - a string containing the user id
  • groupAttributes - (optional) custom shared group attributes

For more information, see Group id and attributes in the Users doc.

Example

Objective-C

[Outbound identifyGroupWithId:@"UNIQUE GROUP ID" userId:@"UNIQUE USER ID" groupAttributes:@{@"shared_group_attr": @"value for attribute"} andUserAttributes:user];

Swift

Outbound.identifyGroup(withId: "UNIQUE GROUP ID", userId: "UNIQUE USER ID", groupAttributes: ["shared_group_attr": "value for attribute"], andUserAttributes: user)

Create an alias for a user

To reference an identified user with a different user id, use the alias method:

Objective-C

[Outbound alias:@"new_user_id"]

Swift

Outbound.alias("new_user_id")

Now "new_user_id" and the old id both point to the same user record in the Outbound database.

For more information, see Aliasing users in the Users doc.

Enable deep linking

To use the deep-linking capabilities in Outbound push notifications, include the following code in your AppDelegate.m file:

Objective-C

- (BOOL) application:(UIApplication *) application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    // 1. Push the correct ViewController onto the stack based on the url.
    // 2. Return a BOOL representing if this was a valid url.
}

For more information about iOS deep linking, see the Mobile SDK FAQ.

Log out user

You can use the logout method to make Outbound "forget" a user when the user logs out of your app:

Objective-C

[Outbound logout];

Swift

Outbound.logout()

This clears the user data from the cache. It doesn't disable the user's push notification token with Outbound.

Manage push notification tokens

You can use the SDK to disable or register push notification tokens in Outbound.

Disable a token

In some situations, you may want to disable push notifications to your app. For instance, you might not want logged out users to get push notifications. You can use the disableDeviceToken method to disable the token:

Objective-C

[Outbound disableDeviceToken];

Swift

Outbound.disableDeviceToken()
Register a token

You can use registerDeviceToken to re-register the previous token when the user logs back in:

Objective-C

[Outbound registerDeviceToken:nil];

Swift

Outbound.registerDeviceToken(nil)