Iterable's iOS SDK supports features such as push notifications, in-app messages, deep links and Mobile Inbox. It can be used with iOS 9 and higher.
This document describes how to install and configure the SDK to work with Iterable.
Table of contents
To install and configure Iterable's iOS SDK, follow these steps:
- 1. Create a Notification Service Extension (if necessary)
- 2. Install the SDK
- 3. Configure the Notification Service Extension (if necessary)
- 4. Import IterableSDK wherever necessary
- 5. Create a mobile API key
- 6. Initialize the SDK with your API key
-
7. Enable push notifications
- 7.1. Set up iOS push notifications in Iterable
- 7.2. Add the Push Notifications capability to your app
- 7.3. Enable the Remote Notifications background mode
- 7.4. Fetch a device token from Apple and register it with Iterable
- 7.5. Handle incoming push notifications and enable push notification tracking
- 7.6. (Optional) Request authorization to display push notifications
- 8. Enable in-app messages
- 9. Verify that the SDK can communicate with Iterable
- Other information
- Further reading
1. Create a Notification Service Extension (if necessary)
For an iOS app to support push notifications that contain action buttons, images, videos or custom sounds, its Xcode project must contain a Notification Service Extension. It's helpful to set your app's Notification Service Extension target up before installing and configuring the SDK.
To add a Notification Service Extension target to your Xcode project:
Open your app's Xcode project.
Choose File > New > Target.
-
On the iOS tab, select Notification Service Extension:
Click Next.
Provide all necessary configuration information for the Notification Service Extension.
Click Finish.
Next, install the SDK using one of the methods described below. Then, configure the Notification Service Extension
2. Install the SDK
To install the SDK, use the Swift Package Manager, CocoaPods, Carthage, or install it manually.
2.1. Install the SDK with the Swift Package Manager
The Swift Package Manager is an Xcode tool that installs project dependencies. To use it to install Iterable's iOS SDK, follow these steps:
NOTES
The Swift Package Manager can install versions 6.2.0 and higher of Iterable's iOS SDK.
In Xcode, navigate to File > Swift Packages > Add Package Dependency.
In the Choose Package Repository window, enter
https://github.com/iterable/swift-sdk
. Click Next.Select an SDK version (by default, Xcode selects the latest stable version). Click Next.
When prompted to add packages to your app, check IterableSDK. In its Add to Target column, select the name of your app's target.
If you will send push notifications that have action buttons, images, video or custom sounds, check IterableAppExtensions. In its Add to Target column, select your project's Notification Service Extension target.
Click Finish.
2.2. Install the SDK with CocoaPods
To use CocoaPods to install Iterable's iOS SDK, follow these steps:
-
If your project does not yet have a Podfile, create one:
In the terminal, navigate to the directory containing your project's .xcodeproj file.
Run this command:
pod init
.
-
Edit the Podfile:
In this file, add the Iterable-iOS-SDK pod to your project's app target.
If your will send push notifications that contain action buttons, images, videos or custom sounds, add the Iterable-iOS-AppExtensions pod to your project's Notification Service Extension.
-
After these changes, your Podfile should look similar to the following:
platform :ios, '11.0' use_frameworks! target '<YOUR_APP_TARGET>' do pod 'Iterable-iOS-SDK' end target '<YOUR_NOTIFICATION_EXTENSION_TARGET>' do pod 'Iterable-iOS-AppExtensions' end
You must include
use_frameworks!
in your Podfile, regardless of whether your app is based on Swift or Objective-C. If your project cannot use this option, install the SDK manually.
In the terminal, run
pod install
to install the pods you configured in the previous step. If you see errors, trypod install --repo-update
.Your project now has an .xcworkspace file. Use this file to open your project, instead of its .xcodeproj file.
For more information, read the CocoaPods documentation.
2.3. Install the SDK with Carthage
To use Carthage to install Iterable's iOS SDK, follow these steps:
2.3.1. Add IterableSDK.framework
First, add IterableSDK.framework to your project:
Create a Cartfile in the same directory as your .xcodeproj or .xcworkspace file.
-
Add this line to the Cartfile:
github "Iterable/swift-sdk"
Open a terminal window. In it, navigate to the same directory as your Cartfile.
Run this command:
carthage update
.From the terminal, open a Finder window:
open .
. In this window, navigate to the Carthage/Build/iOS subdirectory. Keep this window open.Open your app's Xcode project.
From the Finder window opened above, drag IterableSDK.framework onto Xcode's Project Navigator (far left column). When prompted, add the framework to your app target.
In Xcode's Project Navigator, select the top item, which corresponds to the project itself.
Under Targets, select your app.
Navigate to Build Phases.
Add a build phase by clicking + and selecting New Run Script Phase. A Run Script section will appear.
-
In the new Run Script section, add this command in the text area:
/usr/local/bin/carthage copy-frameworks
-
In the Input Files section, click + and add:
$(SRCROOT)/Carthage/Build/iOS/IterableSDK.framework
-
In the Output Files section, add the path to the copied framework:
$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/IterableSDK.framework
2.3.2. Add IterableAppExtensions.framework
If you will send push notifications that have action buttons, images, videos or custom sounds, follow these steps, too:
Open your app's Xcode project.
From the Finder window opened in the previous section, drag IterableAppExtensions.framework onto Xcode's Project Navigator (far left column). When prompted, add the framework to your Notification Service Extension target.
In Xcode's Project Navigator, select the top item, which corresponds to the project itself.
Under Targets, select your Notification Service Extension.
Navigate to Build Phases.
Add a build phase by clicking + and selecting New Run Script Phase. A Run Script section will appear.
-
In the new Run Script section, in the script text area, add this command:
/usr/local/bin/carthage copy-frameworks
-
In the Input Files section, click + and add this path:
$(SRCROOT)/Carthage/Build/iOS/IterableAppExtensions.framework
-
In the Output Files section, add the path to the copied framework:
$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/IterableAppExtensions.framework
2.4. Install the SDK manually
To manually install Iterable's iOS SDK, follow the steps below.
2.4.1. Manually add IterableSDK.framework
First, install IterableSDK.framework:
Download the IterableSDK.zip file associated with a release of Iterable's iOS SDK.
Unzip this file, which contains IterableSDK.framework.
Copy IterableSDK.framework to a directory somewhere in the hierarchy hierarchy associated with your project's .xcodeproj file.
In Xcode's Project Navigator (far left column), select the top item (which corresponds to the project itself).
Under Targets, select your app.
-
On the General tab, find the Frameworks, Libraries, and Embedded Content section. In it, add IterableSDK.framework by clicking + > Add Other > Add Files and selecting the framework.
2.4.2. Manually add IterableAppExtensions.framework
If you will send push notifications that contain action buttons, images, videos, or custom sounds, follow these steps to manually install IterableAppExtensions.framework:
Download the IterableAppExtensions.zip file associated with the same Iterable iOS SDK release referenced above.
Unzip this file, which contains IterabeAppExtensions.framework.
Copy IterableAppExtensions.framework to a directory in the hierarchy associated with your project's .xcodeproj file.
In Xcode's Project Navigator (far left column), select the top item (which corresponds to the project itself).
Under Targets, select the Notification Service Extension.
-
On the General tab, find the Frameworks and Libraries section. In it, add IterableAppExtensions.framework by clicking + > Add Other > Add Files and selecting the framework.
3. Configure the Notification Service Extension (if necessary)
If you added a Notification Service Extension to your project (above),
you can now set it up to handle media attachments and action buttons. To do this,
use the ITBNotificationServiceExtension
class provided by Iterable's iOS SDK:
Open the
NotificationService
class (auto-generated by Xcode when you added the Notification Service Extension to your project).-
For Swift-based projects:
Add an import:
import IterableAppExtensions
.-
Update
NotificationService
so that it extendsITBNotificationServiceExtension
, and contains no other code:import UserNotifications import IterableAppExtensions class NotificationService: ITBNotificationServiceExtension { }
-
For Objective-C projects:
Add an import:
@import IterableAppExtensions;
.-
Configure the class so that it's similar to the following:
// File: NotificationService.m #import "NotificationService.h" @import IterableAppExtensions; @interface NotificationService () @property (nonatomic, strong) ITBNotificationServiceExtension *baseExtension; @end @implementation NotificationService - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { self.baseExtension = [[ITBNotificationServiceExtension alloc] init]; [self.baseExtension didReceiveNotificationRequest:request withContentHandler:contentHandler]; } - (void)serviceExtensionTimeWillExpire { [self.baseExtension serviceExtensionTimeWillExpire]; } @end
4. Import IterableSDK wherever necessary
To use Iterable's iOS SDK in your app's code, import it at the top of any Swift or Objective-C files that reference it. For example:
Swift
// In AppDelegate.swift and any other file where you're using IterableSDK import IterableSDK
Objective-C
// In AppDelegate.m and any other file where you're using IterableSDK @import IterableSDK;
5. Create a mobile API key
To make calls to Iterable's's API, the SDK needs a Mobile API key. To learn how to create one, read API Keys
WARNING
Never embed Standard API keys in client-side code (whether JavaScript, a mobile application or otherwise), since they can be used to access all of your project's data. For a mobile app, use a Mobile API key (if possible, we recommend using JWT authentication for additional security).
If necessary, use different API keys for debug and production builds.
6. Initialize the SDK with your API key
In your app delegate's application(_:didFinishLaunchingWithOptions:)
method, call initialize(apiKey:launchOptions:config:)
. Pass your Iterable API
key as a parameter:
Swift
let config = IterableConfig() IterableAPI.initialize(apiKey: "<YOUR_API_KEY>", launchOptions: launchOptions, config: config)
Objective-C
IterableConfig *config = [[IterableConfig alloc] init]; [IterableAPI initializeWithApiKey:@"<YOUR_API_KEY>" launchOptions:launchOptions config:config]
NOTES
-
IterableConfig
provides configuration and customization options for the Iterable SDK. You'll use it later to set up push notifications and in-app messages. - Earlier versions of the SDK required you to set the
IterableAPI.pushIntegrationName
property. This property now defaults to the bundle ID of the app, and it's not necessary to modify it unless you're using a custom integration name (different from the bundle ID) in Iterable. To view your existing integrations, navigate to Settings > Mobile Apps.
If you're using a JWT-Enabled API Key, you'll also need to implement the auth token requested callback to provide a valid JWT (that you've fetched from your server) for the current user to Iterable's SDK:
Swift
class YourAuthDelegate: IterableAuthDelegate { func onAuthTokenRequested(completion: @escaping AuthTokenRetrievalHandler) { // insert your implementation here: // var token = customCustomerImplementation.getTokenFromBackend() // ... completion(token) } } let authDelegate = YourAuthDelegate() let config = IterableConfig() config.authDelegate = authDelegate IterableAPI.initialize(apiKey: "<YOUR_API_KEY>", launchOptions: launchOptions, config: config)
Objective-C
// YourAuthDelegate.h @import IterableSDK; @interface YourAuthDelegate: NSObject<IterableAuthDelegate> @end // YourAuthDelegate.m #import "YourAuthDelegate.h" @implementation YourAuthDelegate - (void)onAuthTokenRequestedWithCompletion:(void (^ _Nonnull)(NSString * _Nullable))completion { completion(@"<AUTH-TOKEN>"); } @end
To make requests to Iterable's API using a JWT-enabled API key, you should first
fetch a valid JWT for your app's current user from your own server, which must
generate it. onAuthTokenRequested
provides this JWT to Iterable's iOS SDK,
which can then append the JWT to subsequent API requests. The SDK automatically
calls onAuthTokenRequested
at various times:
- When your app sets the user's email or user ID.
- When your app updates the user's email.
- Before the current JWT expires (at a configurable interval set by
expiringAuthTokenRefreshPeriod
, in seconds, onIterableConfig
). - When your app receives a 401 response from Iterable's API with a
InvalidJwtPayload
error code. (however, if the SDK receives a second consecutive 401 with anInvalidJwtPayload
error when it makes a request with the new token, it won't call theauthHandler
again until you callsetEmail
orsetUserId
.
7. Enable push notifications
IMPORTANT
Iterable sends push notifications to iOS apps for two reasons:
- When you send push notification campaigns
- Silently, to tell the app to download new in-app messages
Because Iterable uses silent push notifications to help deliver in-app messages, configure your app to support push notifications even if you do not plan to send push notification campaigns.
To enable push notifications, follow the steps described below.
7.1. Set up iOS push notifications in Iterable
Follow the instructions in Iterable's Setting up iOS Push Notifications guide. This document describes how to configure your iOS app's App ID to use push notifications, and how to set up a mobile app (and associated push integration) in Iterable's web app.
7.2. Add the Push Notifications capability to your app
Follow Apple's instructions to add the Push Notifications capability to your app.
7.3. Enable the Remote Notifications background mode
Follow Apple's instructions to enable the Remote Notifications background mode in your app.
7.4. Fetch a device token from Apple and register it with Iterable
For Iterable to send push notifications to an iOS device, it must know the unique token assigned to that device by Apple.
By default, Iterable's SDK automatically fetches this token from Apple when the
application's code sets IterableAPI.email
or IterableAPI.userId
(which also
disables the device token for the previous email
or userId
, preventing Iterable
from sending push notifications to that user on that device). To fetch the token,
the SDK calls registerForRemoteNotifications()
on UIApplication
.
NOTES
If you set IterableConfig.autoPushRegistration
to false
, the SDK does not
automatically register for a device token. In this case:
- Call
registerForRemoteNotifications()
to register for a token when necessary. - To manually disable push notifications for the current user, call
IterableAPI.disableDeviceForCurrentUser()
.
After fetching a device token, iOS passes it to the application(_:didRegisterForRemoteNotificationsWithDeviceToken:)
method on the app delegate. Configure this method to register the token with
Iterable's SDK, which saves it the user's Iterable profile:
Swift
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { IterableAPI.register(token: deviceToken) }
Objective-C
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [IterableAPI registerToken:deviceToken]; }
7.5. Handle incoming push notifications and enable push notification tracking
To handle incoming push notifications, and to allow Iterable to track events when a user interacts with push notifications, follow these steps:
-
For some object in your app, conform to the
UNUserNotificationCenterDelegate
protocol (apps commonly use the app delegate for this purpose). Import theUserNotifications
framework, indicate that the class conforms to the protocol, and implement these methods:-
userNotificationCenter(_:willPresent:withCompletionHandler:)
This method can be used to allow your app to display incoming push notifications when it is in the foreground.
-
userNotificationCenter(_:didReceive:withCompletionHandler:)
iOS calls this method when a user interacts with a push notification. From here, Iterable's SDK can create events associated with these interactions.
-
Set this object as the delegate for the current
UNUserNotificationCenter
.
For example, Iterable's Swift and Objective-C sample projects have app delegate code similar to the following:
Swift
class AppDelegate: UIResponder, UIApplicationDelegate { // ... private func setupNotifications() { UNUserNotificationCenter.current().delegate = self // ... } // ... } extension AppDelegate: UNUserNotificationCenterDelegate { public func userNotificationCenter(_: UNUserNotificationCenter, willPresent _: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .badge, .sound]) } public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { IterableAppIntegration.userNotificationCenter(center, didReceive: response, withCompletionHandler: completionHandler) } }
Objective-C
@implementation AppDelegate // In its .h file, the AppDelegate class declares that it conforms to UNUsreNotificationCenterDelgate #pragma mark - UNUserNotificationCenterDelegate - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { completionHandler(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound); } - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { [IterableAppIntegration userNotificationCenter:center didReceiveNotificationResponse:response withCompletionHandler:completionHandler]; } // ... #pragma mark - private - (void) setupNotifications { UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; // ... } @end
NOTES
-
setupNotifications()
, shown in the sample code above, is a method specific to the referenced sample apps. In your app, set theUNUserNotificationCenter
delegate wherever convenient. - To learn more about push notifications on iOS, read about the UserNotifications framework.
7.6. (Optional) Request authorization to display push notifications
IMPORTANT
Complete the steps in this section if you plan to use Iterable to send push notification campaigns to your app. Otherwise, they are unnecessary.
iOS apps must have explicit user permission to display push notification alerts, play push notification sounds or update icon badges based on push notifications.
To request this permission, display a prompt by calling the requestAuthorization(options:completionHandler:)
method on UNUserNotificationCenter
.
This is usually done from somewhere in the app delegate. For example:
Swift
UNUserNotificationCenter.current().requestAuthorization(options:[.alert, .badge, .sound]) { (success, error) in if success == true { // ... } }
Objective-C
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { dispatch_async(dispatch_get_main_queue(), ^{ // ... }); } }];
TIP
To learn more about asking for permission to display notifications, read Apple's Asking Permission to Use Notifications guide.
8. Enable in-app messages
To enable in-app messages, follow these steps:
-
Iterable uses silent push notifications to notify an app about new in-app messages awaiting delivery. Because of this, enable push notifications even if you don't plan to send push notification campaigns.
-
Let Iterable's SDK know when the app receives a push notification. This way, it knows to go fetch waiting in-app messages.
To do this, implement the app delegate's
application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
method. In it, call the identically named method onIterableAppIntegration
. For example:Swift
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { IterableAppIntegration.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler) }
Objective-C
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [IterableAppIntegration application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; }
9. Verify that the SDK can communicate with Iterable
To test that your app can communicate with Iterable:
-
In your app's code, after initializing the SDK with your API key, set
IterableAPI.email
to a specific email address:Swift
let config = IterableConfig() IterableAPI.initialize(apiKey: "<YOUR_API_KEY>", launchOptions: launchOptions, config: config) IterableAPI.email = "docs@iterable.com"
Objective-C
IterableConfig *config = [[IterableConfig alloc] init]; [IterableAPI initializeWithApiKey:@"<YOUR_API_KEY>" launchOptions:launchOptions config:config] IterableAPI.email = @"docs@iterable.com";
-
Run the app on a physical device (not the simulator).
Registering for a push notification token from Apple can only be done on a physical device.
-
Check to make sure the new user is visible in Iterable:
Open the Iterable project associated with the API key used in your app's code.
Navigate to Audience > Contact Lookup.
Enter the email address used above and click Search Users.
The user's profile should appear.
If you're having trouble, make sure that you have:
Other information
This section describes other details about Iterable's iOS SDK.
Migrating from a version prior to 6.1.0
Versions 6.1.0+ of the SDK require Xcode 10.2 or higher.
-
In-app messages
-
spawnInAppNotification
The
spawnInAppNotification
method is no longer needed, and will fail to compile. The SDK now displays in-app messages automatically. There is no need to poll the server for new messages. -
Handling manually
To manually control when in-app messages display, set
IterableConfig.inAppDelegate
(anIterableInAppDelegate
object). From itsonNew
method, return.skip
.To get the queue of available in-app messages, call
IterableApi.inAppManager.getMessages()
. Then, callIterableApi.inAppManager.show(message)
to show a specific message. -
Custom actions
The SDK now reserves the
iterable://
URL scheme for Iterable-defined actions handled by the SDK, and theaction://
URL scheme for custom actions handled by the mobile application's custom action handler.If you are currently using the
itbl://
URL scheme for custom actions, the SDK will still pass these actions to the custom action handler. However, support for this URL scheme will eventually be removed (timeline TBD), so it is best to move to theaction://
URL scheme as you can.
-
-
Consolidated deep link URL handling
By default, the SDK handles deep links using the URL delegate assigned to
IterableConfig
.
Further reading
- Identifying the User
- Updating User Profiles
- Tracking Events
- Setting up iOS Push Notifications
- Advanced iOS Push Notifications
- In-App Messages on iOS
- Setting up Mobile Inbox on iOS
- Customizing Mobile Inbox on iOS
- iOS Universal Links
- Deep Links in Push Notifications
- Deferred Deep Linking
- Sample apps that use Iterable's iOS SDK
- Sending Domains, Tracking Domains and Deep Links.
- JWT-Enabled API Keys
Comments
0 comments
Article is closed for comments.