Skip to main content

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.

note

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:

  1. Open your project in Xcode, and go to the "Package Dependencies" tab.
  2. Click the + button under the Packages list.
  3. Enter the repository URL https://github.com/mParticle/mparticle-apple-sdk in the search box on the top right, choose mparticle-apple-sdk from the list of packages, and change "Dependency Rule" to "Up to Next Major Version".
  4. 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, choose mParticle-Apple-SDK-NoLocation.
  5. 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 using import mParticle_Apple_SDK_NoLocation instead of import mParticle_Apple_SDK.

2. Initialize the Rokt SDK

To initialize the SDK, insert the following initialization snippet in your AppDelegate file:

caution
  • Make sure to replace your-key and your-secret with the key and secret provided by your dedicated Rokt team.
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
}

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.

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")

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.

MParticle.sharedInstance().logScreen(
"homepage",
eventInfo: ["custom-attribute": custom-value]
)

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

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)

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.

let roktConfig = MPRoktConfig()
roktConfig.colorMode = .light

MParticle.sharedInstance().rokt.selectPlacements("RoktExperience", attributes: attributes, embeddedViews: nil, callbacks: nil, config: roktConfig)
note

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

FunctionPurpose
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.

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)
note

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)")
}
EventDescriptionParams
ShowLoadingIndicatorTriggered before the SDK calls the Rokt backend
HideLoadingIndicatorTriggered when the SDK receives a success or failure from the Rokt backend
OfferEngagementTriggered when the user engages with the offerplacementId: String
PositiveEngagementTriggered when the user positively engages with the offerplacementId: String
FirstPositiveEngagementTriggered when the user positively engages with the offer for the first timeplacementId: String, setFulfillmentAttributes: func (attributes: [String: String])
PlacementInteractiveTriggered when a placement has been rendered and is interactableplacementId: String
PlacementReadyTriggered when a placement is ready to display but has not rendered content yetplacementId: String
PlacementClosedTriggered when a placement is closed by the userplacementId: String
PlacementCompletedTriggered 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
PlacementFailureTriggered when a placement could not be displayed due to some failure or when no placements are available to showplacementId: String (optional)
OpenUrlTriggered when the user presses a URL that is configured to be sent to the partner appplacementId: 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
ValueDescription
lightApplication is in Light Mode
darkApplication is in Dark Mode
systemApplication defaults to System Color Mode
// 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)

CacheConfig object

ParameterDescription
cacheDurationOptional 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.
cacheAttributesOptional attributes to be used as cache key. If null, all the attributes sent in Rokt.execute will be used as the cache key.
// 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)

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.

if let event = MPEvent(name: "Video Watched", type: .navigation) {
event.customAttributes = ["category": "Destination Intro", "title": "Paris"]
MParticle.sharedInstance().logEvent(event)
}

The supported custom event types are:

  • navigation - Track user navigation flows and page transitions within your app
  • location - Record user location-based interactions and movements
  • search - Capture search queries and search-related user actions
  • transaction - Log financial transactions and purchase-related activities
  • userContent - Track user-generated content like reviews, comments, or posts
  • userPreference - Record user settings, preferences, and customization choices
  • social - Capture social media interactions and sharing activities

Track commerce events

Tracking a commerce event requires three steps:

  1. Defining the product or products that are being purchased within a variable using MPProduct.init
  2. Create an MPTransactionAttributes object to record details that summarize the transaction
  3. Defining the type of product action and event, and then calling the logEvent method, including your product definition and transaction summary
// 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)

When logging a product action, you must specify one of the following product action types:

  • AddToCart
  • RemoveFromCart
  • Checkout
  • CheckoutOption
  • Click
  • ViewDetail
  • Purchase
  • Refund
  • AddToWishlist
  • RemoveFromWishlist
  • Unknown
Was this article helpful?