Aller au contenu principal

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.

remarque

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:

  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:

attention
  • 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
// 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
}

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:

let identifyRequest = MPIdentityApiRequest.withEmptyUser()
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:

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
}
}

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:

let identifyRequest = MPIdentifyApiRequest.withEmptyUser()
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.

let identifyCallback = {(result: MPIdentifyApiResult?) in
if let user = result?.user {
user.setUserAttribute("example attribute key", value: "example attribute value")
}
}

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:

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:

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)

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.

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

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.

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:

  1. 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
  2. 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.

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

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.

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
Cet article vous a-t-il été utile ?