iOS SDK Integration Guide
This page explains how to implement the iOS SDK for Rokt Ads to deliver more relevant customer experiences at checkout. The SDK allows you to trigger and track these experiences (like displaying offers on confirmation pages) by firing on configured pages and passing user and transaction data back to Rokt for personalization and measurement.
Your dedicated account representative will help configure your account for the iOS SDK. They will provide you with both the key and secret required to initialize the SDK and additional resources needed to render the most relevant experiences for your customers.
These instructions require development resources to complete. If you require additional assistance, please reach out to your Rokt account manager.
1. Add the Rokt SDK to your iOS app
Using either SPM or CocoaPods, include the Rokt SDK in your application:
CocoaPods
To integrate the SDK using CocoaPods, specify it in your Podfile with:
pod 'mParticle-Apple-SDK', '~> 8.0'
pod 'mParticle-Rokt','~> 8.0'
SPM
To integrate the SDK using Swift Package Manager:
- Open your project in Xcode, and go to the "Package Dependencies" tab.
- Click the + button under the Packages list.
- Enter the repository URL
https://github.com/mParticle/mparticle-apple-sdk
in the search box on the top right, choosemparticle-apple-sdk
from the list of packages, and change "Dependency Rule" to "Up to Next Major Version". - Click the "Add Package" button on the bottom right, and choose either the "Package Product" called
mParticle-Apple-SDK
. If you'd like to use a version of the SDK that doesn't include location tracking support, choosemParticle-Apple-SDK-NoLocation
. - Repeat steps 3 & 4 for the Rokt Kit repository URL
https://github.com/mparticle-integrations/mparticle-apple-integration-rokt.git
.- If you choose the
mParticle-Apple-SDK-NoLocation
package product, you will need to import the SDK usingimport mParticle_Apple_SDK_NoLocation
instead ofimport mParticle_Apple_SDK
.
- If you choose the
2. Initialize the Rokt SDK
To initialize the SDK, insert the following initialization snippet in your AppDelegate file:
- Make sure to replace
your-key
andyour-secret
with the key and secret provided by your dedicated Rokt team.
- Swift
- Objective-C
import mParticle_Apple_SDK
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Initialize the SDK
let options = MParticleOptions(key: "your-key",
secret: "your-secret")
// Specify the data environment with environment:
// Set it to .development if you are still testing your integration.
// Set it to .production if your integration is ready for production data.
// The default is .autoDetect which attempts to detect the environment automatically
options.environment = .development
// Identify the current user:
let identifyRequest = MPIdentityApiRequest.withEmptyUser()
// If you're using an un-hashed email address, set it in 'email'.
identifyRequest.email = "j.smith@example.com"
// If the user is identified with their email address, set additional user attributes.
options.identifyRequest = identifyRequest
options.onIdentifyComplete = {(result: MPIdentityApiResult?, error: Error?) in
if let user = result?.user {
user.setUserAttribute("example attribute key", value: "example attribute value")
} else {
//handle failure - see "Error Handling" section below
}
}
MParticle.sharedInstance().start(with: options)
return true
}
#import <mParticle_Apple_SDK/mParticle.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Initialize the SDK
MParticleOptions *options = [MParticleOptions optionsWithKey:@"your-key"
secret:@"your-secret"];
// Specify the data environment with environment:
// Set it to MPEnvironmentDevelopment if you are still testing your integration.
// Set it to MPEnvironmentProduction if your integration is ready for production data.
// The default is MPEnvironmentAutoDetect which attempts to detect the environment automatically
options.environment = MPEnvironmentDevelopment;
// Identify the current user:
// If you do not have the user's email address, you can pass in a null value
MPIdentityApiRequest *identifyRequest = [MPIdentityApiRequest requestWithEmptyUser];
// If you're using an un-hashed email address, set it in 'email'.
identifyRequest.email = @"j.smith@example.com";
options.identifyRequest = identifyRequest;
// If the user is identified with their email address, set additional user attributes.
options.onIdentifyComplete = ^(MPIdentityApiResult *_Nullable apiResult, NSError *_Nullable error) {
if (apiResult) {
[apiResult.user setUserAttribute:@"example attribute key"
value:@"example attribute value"];
} else {
//handle failure - see https://docs.mparticle.com/developers/sdk/ios/idsync/#error-handling
}
};
[[MParticle sharedInstance] startWithOptions:options];
return YES;
}
2.1 Identify the User on initialization
When the SDK is initialized, it can identify the current user so that any collected data is correctly attributed to them and to ensure they are shown the most relevant ads based on their behavior.
The SDK initialization script includes an object called identifyRequest:
- Swift
- Objective-C
let identifyRequest = MPIdentityApiRequest.withEmptyUser()
identifyRequest.email = "j.smith@example.com"
options.identifyRequest = identifyRequest
MPIdentityApiRequest *identifyRequest = [MPIdentityApiRequest requestWithEmptyUser];
identifyRequest.email = @"j.smith@example.com";
options.identifyRequest = identifyRequest;
2.2 Set additional user attributes
The initialization script includes a callback function that allows you to set additional user attributes for the user if they are successfully identified with their email address:
- Swift
- Objective-C
options.onIdentifyComplete = {(result: MPIdentityApiResult?, error: Error?) in
if let user = result?.user {
user.setUserAttribute("example attribute key", value: "example attribute value")
} else {
//handle failure - see "Error Handling" section below
}
}
options.onIdentifyComplete = ^(MPIdentityApiResult *_Nullable apiResult, NSError *_Nullable error) {
if (apiResult) {
[apiResult.user setUserAttribute:@"example attribute key"
value:@"example attribute value"];
} else {
//handle failure - see https://docs.mparticle.com/developers/sdk/ios/idsync/#error-handling
}
};
3. Identify the User as data becomes available
Whenever the user provides their email address after the SDK has initialized (for example, when they log in or make a purchase), you should call the identify method to pass their email to Rokt. This ensures that data is correctly attributed to the current user.
3.1 Create an identifyRequest
To identify the user, first create an identifyRequest
object to contain the user’s email address.
If you are providing an un-hashed email address, use:
- Swift
- Objective-C
let identifyRequest = MPIdentifyApiRequest.withEmptyUser()
identifyRequest.email = "j.smith@example.com"
MPIdentifyApiRequest *identifyRequest = [MPIdentifyApiRequest requestWithEmptyUser];
identifyRequest.email = @"j.smith@example.com";
3.2 Set additional user attributes
Next, you have the option of setting additional user attributes when identifying a user by creating a callback function. If the identifyRequest
succeeds, then the user attributes you set with setUserAttribute
are assigned to the user.
- Swift
- Objective-C
let identifyCallback = {(result: MPIdentifyApiResult?) in
if let user = result?.user {
user.setUserAttribute("example attribute key", value: "example attribute value")
}
}
id identityCallback = ^(MPIdentifyApiResult *_Nullable apiResult) {
if (apiResult) {
[apiResult.user setUserAttribute:@"example attribute key"
value:@"example attribute key"];
}
}
3.3 Call the identify method
Finally, after creating your identifyRequest
and your identityCallback
, to set any additional attributes, call the identify method, passing in the identifyRequest
and identityCallback
objects you just created:
- Swift
- Objective-C
MParticle.sharedInstance().identity.identify(identifyRequest, completion: identityCallback)
[[[MParticle sharedInstance] identity] identify:identifyRequest completion:identityCallback];
For example, to identify a user named Jane Smith with the email address j.smith@example.com (and you don't need to hash their email address) you would use:
- Swift
- Objective-C
let identifyRequest = MPIdentifyApiRequest.withEmptyUser()
identifyRequest.email = "j.smith@example.com"
let identifyCallback = {(result: MPIdentifyApiResult?) in
if let user = result?.user {
user.setUserAttribute("example attribute key", value: "example attribute value")
}
}
MParticle.sharedInstance().identity.identify(identifyRequest, completion: identityCallback)
MPIdentifyApiRequest *identifyRequest = [MPIdentifyApiRequest requestWithEmptyUser];
identifyRequest.email = @"j.smith@example.com";
id identityCallback = ^(MPIdentifyApiResult *_Nullable apiResult) {
if (apiResult) {
[apiResult.user setUserAttribute:@"example attribute key"
value:@"example attribute key"];
}
}
[[[MParticle sharedInstance] identity] identify:identifyRequest completion:identityCallback];
4. Track User Attributes
You can use the Rokt SDK to collect user attributes separately from events. User attributes are separate from custom attributes when tracking events. The SDK will associate any user attributes collected in a given session with events triggered in the same session.
To collect user attributes, the following code should be run in your app immediately after initializing the Rokt SDK, and before you log an event.
- Swift
- Objective-C
import mParticle_Apple_SDK
// Retrieve the current user. This will only succeed if you have identified the user during SDK initialization or by calling the identify method.
let currentUser = MParticle.sharedInstance().identity.currentUser
// Once you have successfully set the current user to `currentUser`, you can set user attributes with:
currentUser?.setUserAttribute("custom-attribute-name", value: "custom-attribute-value")
// Note: all user attributes (including list attributes and tags) must have distinct names.
// Rokt recommends setting as many of the following user attributes as possible:
currentUser?.setUserAttribute("firstname", value: "John")
currentUser?.setUserAttribute("lastname", value: "Doe")
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser?.setUserAttribute("mobile", value: "3125551515")
currentUser?.setUserAttribute("age", value: "33")
currentUser?.setUserAttribute("gender", value: "M")
currentUser?.setUserAttribute("city", value: "Brooklyn")
currentUser?.setUserAttribute("state", value: "NY")
currentUser?.setUserAttribute("zip", value: "123456")
currentUser?.setUserAttribute("dob", value: "yyyymmdd")
currentUser?.setUserAttribute("title", value: "Mr")
currentUser?.setUserAttribute("language", value: "en")
currentUser?.setUserAttribute("value", value: "52.25")
currentUser?.setUserAttribute("predictedltv", value: "136.23")
// You can create a user attribute to contain a list of values
currentUser?.setUserAttributeList("favorite-genres", values: ["documentary", "comedy", "romance", "drama"])
// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
currentUser?.removeAttribute("attribute-to-remove")
#import <mParticle_Apple_SDK/mParticle.h>
// Retrieve the current user. This will only succeed if you have identified the user during SDK initialization or by calling the identify method.
MParticleUser *currentUser = [[[MParticle sharedInstance] identity] currentUser];
// Once you have successfully set the current user to `currentUser`, you can set user attributes with:
[currentUser setUserAttribute:@"custom-attribute-name" value:@"custom-attribute-name"];
// Note: all user attributes (including list attributes and tags) must have distinct names.
// Rokt recommends setting as many of the following user attributes as possible:
[currentUser setUserAttribute:@"firstname" value:@"John"];
[currentUser setUserAttribute:@"lastname" value:@"Doe"];
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
[currentUser setUserAttribute:@"mobile" value:@"3125551515"];
[currentUser setUserAttribute:@"age" value:@"33"];
[currentUser setUserAttribute:@"gender" value:@"M"];
[currentUser setUserAttribute:@"city" value:@"Brooklyn"];
[currentUser setUserAttribute:@"state" value:@"NY"];
[currentUser setUserAttribute:@"zip" value:@"123456"];
[currentUser setUserAttribute:@"dob" value:@"yyyymmdd"];
[currentUser setUserAttribute:@"title" value:@"Mr"];
[currentUser setUserAttribute:@"language" value:@"en"];
[currentUser setUserAttribute:@"value" value:@"52.25"];
[currentUser setUserAttribute:@"predictedltv" value:@"136.23"];
// You can create a user attribute to contain a list of values
[currentUser setUserAttribute:@"favorite-genres" values:@[@"documentary", @"comedy", @"romance", @"drama"]];
// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
[currentUser removeUserAttribute:@"attribute-to-remove"];
5. Capture Screen Views
One of the most basic event types you can track is the screen view.
When first integrating with the Rokt SDK, start by implementing screen view tracking. To learn about tracking custom and commerce events, see the Appendix.
Track screen views
One of the most basic event types you can track is the screen view. To log a screen view, call the .logScreen
method, passing in the name of the screen as a string.
The name you pass in should be one of a limited set of pages, like 'homepage'
or 'product detail page'
. You can also include additional custom attributes in the eventInfo
array.
- Swift
- Objective-C
MParticle.sharedInstance().logScreen(
"homepage",
eventInfo: ["custom-attribute": customValue]
)
[[MParticle sharedInstance] logScreen:@"homepage"
eventInfo:@{@"custom-attribute": customValue}];
6. Track Conversions
To track a conversion, run the following code snippet on the most appropriate page that's loaded after a customer converts, such as a purchase confirmation or "thank you" page.
When pasting the code snippet into your site, make sure to:
- Replace the sample user attributes in the
setUserAttribute
calls the actual values for your user or customer. Rokt recommends setting at least the following user attributes:firstname
lastname
zipcode
mobile
- Replace the sample conversion event attributes with with actual values from your conversion event.
When logging a conversion event, you should include as many user attributes and event attributes as possible to improve Rokt's ability to optimize your campaigns.
- Swift
- Objective-C
if let event = MPEvent(name: "conversion", type: .transaction) {
event.customAttributes = [
"conversiontype": "signup", // type of conversion
"confirmationref": "54321", // Transaction ID / Order ID
"amount": "", // Transaction amount e.g. 300.5
"currency": "", // Transaction currency e.g. USD
// You can track your own custom event attributes!
"CUSTOM_EVENT_ATTRIBUTE_NAME" : "CUSTOM_EVENT_ATTRIBUTE_VALUE"
]
MParticle.sharedInstance().logEvent(event)
}
MPEvent *event = [[MPEvent alloc] initWithName:@"conversion" type:MPEventTypeTransaction];
if (event) {
event.customAttributes = @{
@"conversiontype": @"signup", // type of conversion
@"confirmationref": @"54321", // Transaction ID / Order ID
@"amount": @"", // Transaction amount e.g. 300.5
@"currency": @"", // Transaction currency e.g. USD
// You can track your own custom event attributes!
@"CUSTOM_EVENT_ATTRIBUTE_NAME" : @"CUSTOM_EVENT_ATTRIBUTE_VALUE"
};
[[MParticle sharedInstance] logEvent:event];
}
Appendix
Track custom events
You can define and track custom events by calling logEvent
and passing in the event name, the event type, and an optional array containing any custom attributes for the event.
- Swift
- Objective-C
if let event = MPEvent(name: "Video Watched", type: .navigation) {
event.customAttributes = ["category": "Destination Intro", "title": "Paris"]
MParticle.sharedInstance().logEvent(event)
}
MPEvent *event = [[MPEvent alloc] initWithName:@"Video Watched" type:MPEventTypeNavigation];
if (event) {
event.customAttributes = @{
@"category": @"Destination Intro",
@"title": @"Paris"
};
[[MParticle sharedInstance] logEvent:event];
}
The supported custom event types are:
- Swift
- Objective-C
navigation
- Track user navigation flows and page transitions within your applocation
- Record user location-based interactions and movementssearch
- Capture search queries and search-related user actionstransaction
- Log financial transactions and purchase-related activitiesuserContent
- Track user-generated content like reviews, comments, or postsuserPreference
- Record user settings, preferences, and customization choicessocial
- Capture social media interactions and sharing activities
MPEventTypeNavigation
- Track user navigation flows and page transitions within your appMPEventTypeLocation
- Record user location-based interactions and movementsMPEventTypeSearch
- Capture search queries and search-related user actionsMPEventTypeTransaction
- Log financial transactions and purchase-related activitiesMPEventTypeUserContent
- Track user-generated content like reviews, comments, or postsMPEventTypeUserPreference
- Record user settings, preferences, and customization choicesMPEventTypeSocial
- Capture social media interactions and sharing activities
Track commerce events
Tracking a commerce event requires three steps:
- Defining the product or products that are being purchased within a variable using
MPProduct.init
- Create an MPTransactionAttributes object to record details that summarize the transaction
- Defining the type of product action and event, and then calling the
logEvent
method, including your product definition and transaction summary
- Swift
- Objective-C
// 1. Define the product(s)
let product = MPProduct.init(name: "Double Room",
sku: "econ-1",
quantity: 4,
price: 100.00)
// 2. Summarize the transaction
let attributes = MPTransactionAttributes.init()
attributes.transactionId = "foo-transaction-id"
attributes.revenue = 430.00
attributes.tax = 30.00
// 3. Log the commerce event.
// Several types of "actions" are supported, such as AddToCart and Checkout. This example uses the Purchase product action.
let action = MPCommerceEventAction.purchase;
let event = MPCommerceEvent.init(action: action, product: product)
event.transactionAttributes = attributes
MParticle.sharedInstance().logEvent(event)
// 1. Define the product(s)
MPProduct *product = [[MPProduct alloc] initWithName:@"Double Room"
sku:@"econ-1"
quantity:@4
price:@100.00];
// 2. Summarize the transaction
MPTransactionAttributes *attributes = [[MPTransactionAttributes alloc] init];
attributes.transactionId = @"foo-transaction-id";
attributes.revenue = @430.00;
attributes.tax = @30.00;
// 3. Log the commerce event
MPCommerceEvent *event = [[MPCommerceEvent alloc] initWithAction:MPCommerceEventActionPurchase
product:product];
event.transactionAttributes = attributes;
[[MParticle sharedInstance] logEvent:event];
When logging a product action, you must specify one of the following product action types:
- Swift
- Objective-C
AddToCart
RemoveFromCart
Checkout
CheckoutOption
Click
ViewDetail
Purchase
Refund
AddToWishlist
RemoveFromWishlist
Unknown
MPCommerceEventActionAddToCart
MPCommerceEventActionRemoveFromCart
MPCommerceEventActionCheckout
MPCommerceEventActionCheckoutOption
MPCommerceEventActionClick
MPCommerceEventActionViewDetail
MPCommerceEventActionPurchase
MPCommerceEventActionRefund
MPCommerceEventActionAddToWishlist
MPCommerceEventActionRemoveFromWishlist
MPCommerceEventActionUnknown