iOS SDK Integration Guide
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. Shopify stores can set up a Rokt placement in seconds using the Rokt Ecommerce app — no coding needed!
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
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;
[[MParticle sharedInstance] startWithOptions:options];
return YES;
}
3. 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"];
4. Capture Funnel Events
The Rokt SDK allows you implement event tracking to collect data describing your users' journeys through your app. You can then use this data to optimize your users' experience.
There are three primary event types you can record with the SDK:
- Screen View Events: These are events you can trigger when a page of your app is loaded.
- Custom Events: These are freeform events you create to track information specific to your app.
- Commerce Events: These are events specific to ecommerce that can describe the different stages of the shopping experience, including adding items to a cart and making a final purchase.
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": custom-value]
)
[[MParticle sharedInstance] logScreen:@"homepage"
eventInfo:@{@"custom-attribute": customValue}];
5. Show a Placement
The main value of the Rokt SDK is unlocked through the selectPlacements
method, which serves a placement (or layout) that is hyper-relevant to your customers based on attributes you provide.
Once the Rokt integration has been initialized, you can call the selectPlacements
method from the page where your layout will be rendered. It should be called as early as possible, and once all required attributes are available, to ensure the best experience for your users.
When calling selectPlacements you should provide at least the email
, firstname
, lastname
, billingzipcode
and confirmationref
attributes to provide your users with the most relevent placement.
Overlay placements
- Swift
- Objective-C
import mParticle_Apple_SDK
let attributes = [
"email": "test@gmail.com",
"firstname": "Jenny",
"lastname": "Smith",
"billingzipcode": "07762",
"confirmationref": "54321"
]
MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes)
#import <mParticle_Apple_SDK/mParticle.h>
NSDictionary *attributes = @{
@"email": @"test@gmail.com",
@"firstname": @"Jenny",
@"lastname": @"Smith",
@"billingzipcode": @"07762",
@"confirmationref": @"54321"
};
[[[MParticle sharedInstance] rokt] selectPlacements:@"RoktExperience" attributes:attributes];
You may also want to pass optional parameters such as MPRoktConfig
which will allow you to customize the placement UI, primarily on whether or not the app is in dark or light mode. Additional optional parameters such as embedded views and callbacks are shown lower.
- Swift
- Objective-C
let roktConfig = MPRoktConfig()
roktConfig.colorMode = .light
MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: nil, callbacks: nil, config: roktConfig)
MPRoktConfig *roktConfig = [[MPRoktConfig alloc] init];
roktConfig.colorMode = MPColorModeLight;
[[MParticle sharedInstance].rokt selectPlacements:@"RoktExperience" attributes:attributes embeddedViews:nil config:roktConfig callbacks:callbacks];
If you want to update the identifier RoktExperience
or embedded identifier RoktEmbedded1
with a different value, contact your Rokt account manager to ensure Rokt placements are configured consistently.
Optional functions
Function | Purpose |
---|---|
Rokt.close() | Used to auto-close overlay placements. |
Embedded placements
Embedded placements share all of the same recommendations and requirements as overlay placements above but allow you to embed the placement views in your UI. We will also use this section to provide examples for the various advanced features allowed through Rokt.
The MPRoktEventCallback
class, which is passed to Rokt through the callbacks
parameter, allow you to respond to various events that occur when generating and displaying a placement.
- Swift
- Objective-C
import mParticle_Apple_SDK
let attributes = [
"email": "test@gmail.com",
"firstname": "Jenny",
"lastname": "Smith",
"billingzipcode": "07762",
"confirmationref": "54321"
]
let roktFrame = CGRect(x: 0, y: 0, width: 320, height: 50)
let roktView = MPRoktEmbeddedView(frame: roktFrame)
let embeddedViews = ["RoktEmbedded1": roktView]
let roktConfig = MPRoktConfig()
roktConfig.colorMode = .light
let callbacks = MPRoktEventCallback()
callbacks.onLoad = {
// Optional callback for when the Rokt placement loads
}
callbacks.onUnLoad = {
// Optional callback for when the Rokt placement unloads
}
callbacks.onShouldShowLoadingIndicator = {
// Optional callback to show a loading indicator
}
callbacks.onShouldHideLoadingIndicator = {
// Optional callback to hide a loading indicator
}
callbacks.onEmbeddedSizeChange = { (placement: String, size: CGFloat) in
// Optional callback to get selectedPlacement and height required by the placement every time the height of the placement changes
}
MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: embeddedViews, config: roktConfig, callbacks: callbacks)
#import <mParticle_Apple_SDK/mParticle.h>
NSDictionary *attributes = @{
@"email": @"test@gmail.com",
@"firstname": @"Jenny",
@"lastname": @"Smith",
@"billingzipcode": @"07762",
@"confirmationref": @"54321"
};
CGRect roktFrame = CGRectMake(0, 0, 320, 50);
MPRoktEmbeddedView *roktView = [[MPRoktEmbeddedView alloc] initWithFrame:roktFrame];
NSDictionary *embeddedViews = @{@"RoktEmbedded1": roktView};
MPRoktConfig *roktConfig = [[MPRoktConfig alloc] init];
roktConfig.colorMode = MPColorModeLight;
MPRoktEventCallback *callbacks = [[MPRoktEventCallback alloc] init];
callbacks.onLoad = ^{
// Optional callback for when the Rokt placement loads
};
callbacks.onUnLoad = ^{
// Optional callback for when the Rokt placement unloads
};
callbacks.onShouldShowLoadingIndicator = ^{
// Optional callback to show a loading indicator
};
callbacks.onShouldHideLoadingIndicator = ^{
// Optional callback to hide a loading indicator
};
callbacks.onEmbeddedSizeChange = ^(NSString *placement, CGFloat size) {
// Optional callback to get selectedPlacement and height required by the placement every time the height of the placement changes
};
[[MParticle sharedInstance].rokt selectPlacements:@"RoktExperience" attributes:attributes embeddedViews:embeddedViews config:roktConfig callbacks:callbacks];
For a full list of supported attributes, see Data Attributes.
Your dedicated Rokt team will configure your placement layouts for you so they match your brand and UX styleguide.
Global events API
The SDK provides the status of the SDK through the Rokt.globalEvents
API.
import Rokt_Widget
Rokt.globalEvents() { roktEvent in
if let initEvent = roktEvent as? RoktEvent.InitComplete {
print("Rokt init completed with status: \(initEvent.success)")
}
}
Events
The SDK also provides the events on each page through Rokt.events
API.
import Rokt_Widget
Rokt.events(viewName: "RoktExperience") { roktEvent in
print("Rokt event received \(roktEvent)")
}
Event | Description | Params |
---|---|---|
ShowLoadingIndicator | Triggered before the SDK calls the Rokt backend | |
HideLoadingIndicator | Triggered when the SDK receives a success or failure from the Rokt backend | |
OfferEngagement | Triggered when the user engages with the offer | placementId: String |
PositiveEngagement | Triggered when the user positively engages with the offer | placementId: String |
FirstPositiveEngagement | Triggered when the user positively engages with the offer for the first time | placementId: String, setFulfillmentAttributes: func (attributes: [String: String]) |
PlacementInteractive | Triggered when a placement has been rendered and is interactable | placementId: String |
PlacementReady | Triggered when a placement is ready to display but has not rendered content yet | placementId: String |
PlacementClosed | Triggered when a placement is closed by the user | placementId: String |
PlacementCompleted | Triggered when the offer progression reaches the end and no more offers are available to display. Also triggered when cache is hit but the retrieved placement will not be displayed as it has previously been dismissed | placementId: String |
PlacementFailure | Triggered when a placement could not be displayed due to some failure or when no placements are available to show | placementId: String (optional) |
OpenUrl | Triggered when the user presses a URL that is configured to be sent to the partner app | placementId: String, url: String |
Appendix
Debugging
You can enable debugging logs by setting the following configuration option when initializing the SDK:
Rokt.setLoggingEnabled(enable: true)
After implementing placements and screen view tracking by following the instructions above, you may want to implement additional event tracking.
Using App Configurations
Applications can now send configuration settings from their own application environment. This allows the iOS SDK to use application custom configurations instead of relying solely on system defaults.
ColorMode object
Value | Description |
---|---|
light | Application is in Light Mode |
dark | Application is in Dark Mode |
system | Application defaults to System Color Mode |
- Swift
- Objective-C
// if application supports only Light Mode.
let roktConfig = MPRoktConfig()
roktConfig.colorMode = .light
MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: nil, callbacks: nil, config: roktConfig)
// if application supports only Light Mode.
MPRoktConfig *roktConfig = [[MPRoktConfig alloc] init];
roktConfig.colorMode = MPColorModeLight;
[[MParticle sharedInstance].rokt selectPlacements:@"RoktExperience" attributes:attributes embeddedViews:embeddedViews config:roktConfig callbacks:callbacks];
CacheConfig object
Parameter | Description |
---|---|
cacheDuration | Optional TimeInterval for which the Rokt SDK should cache the experience. Maximum allowed value is 90 minutes and the default (if value is not provided or invalid) is 90 minutes. |
cacheAttributes | Optional attributes to be used as cache key. If null, all the attributes sent in Rokt.execute will be used as the cache key. |
- Swift
- Objective-C
// to cache the experience for 1200 seconds, using email and orderNumber attributes as the cache key.
let roktConfig = MPRoktConfig()
roktConfig.cacheDuration = TimeInterval(1200)
roktConfig.cacheAttributes = ["email": "j.smith@example.com", "orderNumber": "123"]
MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: nil, callbacks: nil, config: roktConfig)
// to cache the experience for 1200 seconds, using email and orderNumber attributes as the cache key.
MPRoktConfig *roktConfig = [[MPRoktConfig alloc] init];
roktConfig.cacheDuration = @(1200);
roktConfig.cacheAttributes = @{@"email": @"j.smith@example.com", @"orderNumber": @"123"};
[[MParticle sharedInstance].rokt selectPlacements:@"RoktExperience" attributes:attributes embeddedViews:embeddedViews config:roktConfig callbacks:callbacks];
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