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.

The iOS SDK supports iOS 9 and above.

This document covers the following topics:

Add the Connect SDK to Objective-C projects

Install the SDK

The Connect SDK supports CocoaPods, and Carthage.

CocoaPods

Add the following to your Podfile:

pod 'ZendeskConnect'

Next run:

pod install
Carthage

Add this line to your Cartfile:

github "zendesk/connect-ios-sdk"

To add the ZendeskConnect.framework to your project, follow the steps for iOS in the Carthage docs on GitHub.

Include the SDK in your project

Merge the following code into your AppDelegate.m file:

#import "AppDelegate.h"
#import <ZendeskConnect/ZendeskConnect-Swift.h>
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate () <UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Enable logging
    [ZCNLogger setEnabled:YES];
    // 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.
    [[ZCNConnect instance] 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.
     [[ZCNConnect instance] registerPushToken: deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    if ([[ZCNConnect instance] isConnectNotificationWithUserInfo:userInfo]) {
        [[ZCNConnect instance] 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 {
    if ([[ZCNConnect instance] isConnectNotificationResponse:response]) {
        [[ZCNConnect instance] handleNotificationResponse:response completion:completionHandler];
    } else {
        // Handle non-Connect notifications here
        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 'ZendeskConnect'
    
  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.

Carthage

Add this line to your Cartfile:

github "zendesk/connect-ios-sdk"

To add the ZendeskConnect.framework to your project, follow the steps for iOS in the Carthage docs on GitHub.

Include the SDK in your project

In previous versions of the Connect SDK, a bridging header was required to include the Connect SDK in Swift projects. As of version v2.0.0, the Connect SDK is written in Swift, which means no bridging header is required.

Merge the following code into your AppDelegate.swift file:

import UIKit
import UserNotifications
import ZendeskConnect

@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
        }
        Connect.instance.init(privateKey: "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.
        Connect.instance.registerPushToken(deviceToken)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if Connect.instance.isConnectNotification(userInfo: userInfo) {
            Connect.instance.handleNotification(userInfo: userInfo) { success 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) {
        if Connect.instance.isConnectNotificationResponse(response) {
            Connect.instance.handleNotificationResponse(response) {
                completionHandler()
            }
        } else {
            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 identifyUser method to send user data to Connect.

Example

Objective-C

ZCNUser *newUser = [[ZCNUser alloc] initWithFirstName:@"John"
                                                 lastName:@"Smith"
                                                    email:@"john@smith.com"
                                               attributes:@{@"San Francisco": @"city", @"spicy": @"taste_preference"}
                                                   userId:@"12345"
                                               previousId:nil
                                              phoneNumber:@"5555555555"
                                                  groupId:nil
                                          groupAttributes:nil
                                                 timezone:nil
                                                      gcm:nil
                                                     apns:nil];

[[ZCNConnect instance] identifyUser: newUser];

Swift

let user = User(firstName: "Jane",
                lastName: "Doe",
                email: "jdoe@example.com",
                attributes: ["San Francisco": "city", "spicy": "taste_preference"],
                userId: "54321")

Connect.instance.identifyUser(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
Examples

Objective-C

ZCNEvent *event = [ZCNEventFactory createEventWithEvent:@"eventName" properties:@{@"foo": @"bar"}];
[[ZCNConnect instance] trackEvent:event];

Swift

let event = EventFactory.createEvent(event: "eventName", properties: ["foo": "bar"])
Connect.instance.trackEvent(event)

For more information, see Events.

Create an alias for a user

To reference an identified user with a different user ID, use the following:

Objective-C

ZCNEvent *aliasedUser = [user aliasedWithAliasId:@"new_user_id"];
[[ZCNConnect instance] identifyUser: aliasedUser];

Swift

let aliasedUser = user.aliased(aliasId: "new_user_id")
Connect.instance.identifyUser(aliasedUser)

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.

Get User

To retrieve details about the currently active user:

Objective-C

[[ZCNConnect instance] currentUser];

Swift

Connect.instance.user

Log out user

You can use the logoutUser method to make Connect "forget" a user when the user logs out of your app. This clears the user data from the cache and calls disablePushToken to disable the user's push notification token with Connect.

Objective-C

[[ZCNConnect instance] logoutUser];

Swift

Connect.instance.logoutUser()

Manage push notification tokens

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

Register a token

You can use registerPushToken to register a token:

Objective-C

[[ZCNConnect instance] registerPushToken:deviceToken];

Swift

Connect.instance.registerPushToken(deviceToken)
Disable a token

Use the disablePushToken method if you no longer want to send push notifications to the user's device:

Objective-C

[[ZCNConnect instance] disablePushToken];

Swift

Connect.instance.disablePushToken()