iOS SDK

You can integrate the Connect iOS SDK in your iOS app to send user and event data to Zendesk Connect 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 Connect SDK to Objective-C projects

Install the SDK

The Connect 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>
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate () <UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Connect 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 Connect account.
    [Outbound initWithPrivateKey:@"PRIVATE_KEY"];
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    return YES;
}

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

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    if ([Outbound isOutboundNotification:userInfo]) {
        [Outbound handleNotificationWithUserInfo:userInfo completion:^(BOOL success) {
            completionHandler(success ? UIBackgroundFetchResultNewData : UIBackgroundFetchResultFailed);
        }];
    } else {
        // Handle non-Connect notifications here
        completionHandler(UIBackgroundFetchResultNoData);
    }
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    // Optionally allow showing notifications while the app is in the foreground.
    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    [Outbound handleNotificationResponse:response];
    completionHandler();
}

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 Connect SDK to Swift projects

Install the SDK

The Connect 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 'Connect'
    
  5. Save the Podfile and run the following command in Terminal:

    $ pod install
    

    Wait for CocoaPods to finish downloading and installing the Connect 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 Connect 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

Merge the following code into your AppDelegate.swift file:

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        // Connect 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.
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
        }
        Outbound.initWithPrivateKey("PRIVATE_KEY")
        return true
    }

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

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if (Outbound.isOutboundNotification(userInfo)) {
            Outbound.handleNotification(userInfo: userInfo, completion: {(_ success: Bool) -> Void in
                completionHandler(success ? .newData : .failed)
            })
        } else {
            // Handle notifications here.
            completionHandler(.newData);
        }
    }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // Optionally allow showing notifications while the app is in the foreground.
        completionHandler([.alert, .sound, .badge])
    }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        Outbound.handle(response)
        completionHandler()
    }
}

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

Identify a user

Use the identifyUserWithId method to send user data to Connect. 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 Connect. 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. Connect 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.

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 Connect database.

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

Enable deep linking

To use the deep-linking capabilities in Connect 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 Connect "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 Connect.

Manage push notification tokens

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

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)