Customer Data Platform Mobile SDK

The Customer Data Platform Mobile SDK makes it possible for you to integrate your mobile applications with the Customer Data Platform to capture rich behavioral and demographic data from end users, including app lifecycle and screen navigation events. Events collected by Customer Data Platform create a unified profile of a customer to enable hyper-personalized engagement across multiple Salesforce clouds - marketing, commerce, service and beyond.

A newer version of the Mobile SDK is available. If you haven’t already implemented the Customer Data Platform Mobile SDK version, we recommend implementing the latest Integrate your Mobile Applications version.

Important

Prerequisites

In order to use the Customer Data Platform Mobile SDK, create a Salesforce data source connector and auto-generated endpoints. Log into your Customer Data Platform application and navigate to the left side panel of the Websites and Mobile Apps screen. Set up your data sources by creating an app connector within the user interface. For additional information, see the Customer Data Platform Implementation Guide.

Use the appSourceId and generated endpoints from your web data connector to initialize the Customer Data Platform Mobile SDK.

Download the SDK

Download the source for the Customer Data Platform Mobile SDK from one of these sources, depending upon your operating system:

Install the SDK

You can add the Customer Data Platform Mobile SDK to your mobile application using CocoaPods or by building the calls into your source code.

CocoaPods

CocoaPods provides a central place where third party libraries can be easily managed for your project. To integrate the Customer Data Platform Mobile SDK with your iOS mobile app using CocoaPods, create a Podfile and add the dependency:
1use_frameworks!
2          
3          target '<Your Target>' do
4             pod 'SALESFORCE-CDP-SDK-IOS-SDK', '~> 1.0'
5          end

Manual Installation

A manual installation requires that you manage all of the dependencies with your own code. Given that multiple libraries are sharing a dependency, but all can specify a different version of it, it’s the mobile app developer’s responsibility to provide the best version of the library that satisfies all dependencies.

Configuring the SDK

Before the Customer Data Platform Mobile SDK can be used to invoke web services using the API, it must be configured. Use the CdpConfigBuilder helper class to build your SDK configuration by providing required settings appId and endpoint. Optionally configure additional settings trackScreens, trackLifecycle, and sessionTimeout.
1let config = CdpConfigBuilder(appId: {REPLACE WITH APP ID}, endpoint: {REPLACE WITH ENDPOINT})
2       .trackScreens({True|False})
3       .trackLifecycle({True|False})
4       .sessionTimeout({Int})
5       .build()

Configure the SDK

The Customer Data Platform Mobile SDK is ready for use in two steps:
  1. Build the Customer Data Platform Mobile SDK configuration, providing application ID (in UUID format) and Salesforce Tenant Specific Endpoint (TSE) for Customer Data Platform.
    1let config = CdpConfigBuilder(appId: {REPLACE WITH APP ID}, endpoint: 
    2          {REPLACE WITH ENDPOINT}).build()
  2. Initialize the Customer Data Platform Mobile SDK.
    1_ = CdpSdk.configure(config)
    2          Congratulations! The CDP SDK is now configured and ready to use. You can verify that by inspecting the state of the CDP SDK instance:
    3          CdpSdk.shared.state
    4          Example output:
    5          {
    6            "name":"cdp",
    7            "config": {
    8               "sessionDuration":600,
    9               "screenTrackingEnabled":false,
    10               "lifecycleEventTrackingEnabled":false,
    11               "appId":"YOUR APP ID",
    12               "endpoint":"YOUR ENDPOINT"
    13            },
    14            "consentManager":{
    15               "deviceId":"YOUR DEVICE ID",
    16               "consent":"pending"
    17            },
    18            "eventManager":{
    19               "queueSize":0
    20            },
    21            "sessionManager":{
    22               "sessionId":"SESSION ID"
    23            }
    24          }
    Configuration properties that aren’t explicitly set use the default values.

Configuration Parameters

The following table describes Customer Data Platform Mobile SDK configurable settings.

Setting Type Description
appId string Required. The appId setting uniquely identifies your mobile application to the Customer Data Platform platform and must be in format of a valid UUID (universally unique identifier). Providing an invalid appID to the CdpSdkBuilder results in a fatal error.
endpoint string Required. The endpoint setting tells the Customer Data Platform Mobile SDK web service where to send the events being created and tracked. Endpoint must be a valid Customer Data Platform URL in the format:
1https://{tenant specific 
2              endpoint id}.c360a.salesforce.com. [description here of allowed domains]
Providing an invalid endpoint to the CdpSdkBuilder results in a fatal error.
trackScreens boolean Optional. Default is FALSE. Enable trackScreens to automatically track the mobile app ScreenEntry event. The event is collected as an engagement event with eventType "ScreenView" and attribute "screenname".
trackLifecycle boolean Optional. Default is FALSE. Enable trackLifecycle to automatically track AppForegrounded and AppVersionChanged application lifecycle events. Events are collected as engagement events. AppVersionChanged events have eventType "AppUpdate" and attribute "previousVersion". AppForegrounded events have eventType "AppFirstLaunch" or "AppLaunch" with no attributes.
sessionTimeoutInSeconds int Optional. Default is 600. The sessionTimeoutInSeconds setting represents the number of seconds the mobile application can remain in the background before the current session is expired. Session management works like this: When an end user launches the mobile application, the Customer Data Platform Mobile SDK starts a new session that is maintained while the app is in the foreground. If the user sends the mobile application to the background, the SDK starts a timer to expire the current session. If the user brings the mobile app back to the foreground before the session expires, the timer is cleared and the session is continued. Otherwise the session expires.
Next, call the configure method on the CdpSdk object to instantiate a shared instance with the configuration you built.
1let sdk = CdpSdk.configure(config)
The Customer Data Platform Mobile SDK is now ready to collect events. You refer to the Customer Data Platform Mobile SDK singleton instance using CdpSdk.shared.
1CdpSdk.shared
It’s important to note that configuration settings can’t be altered for an initialized Customer Data Platform Mobile SDK instance. If you execute a second call to CdpSdk.configure(), the existing instance is destroyed and a new Customer Data Platform Mobile SDK instance is created.
1// Initially
2        <Cdp.CdpSdk: 0x600001854780>
3          // After reconfiguring
4          <Cdp.CdpSdk: 0x600001865da0>

Logging Levels

Logging is an optional, yet critical, SDK feature that allows the mobile application developer to select the verbosity of the Customer Data Platform Mobile SDK’s output. By default, logging is disabled and must be enabled using the setLogLevel method on the CdpSdk shared instance to define the desired Log Level and the Log Outputter. This results in log capture using the native unified logging system.

Logging Parameters

1CdpSdk.setLogLevel(MCLogLevel.debug, logOutputter: LogOutputter())
Parameter Type Description
logLevel MCLogLevel Required. Defines the depth of detail in log output. Available options: error, warning, debug, none.
logOutputter LogOutputter Required. Defines output. Captures logs using the native unified logging system.

Log Level Definitions

Log Level Default Description
MCLogLevel.error No This log level provides details about unrecoverable errors associated with inability to complete valuable business use cases.
MCLogLevel.warning No This log level indicates the SDK integration might have a problem or it encountered an unusual situation. Warnings are associated with potentially harmful, but recoverable errors.
MCLogLevel.debug No Optional. This log level provides granular, low-level information about how the SDK processes tasks, events, anderror details. Debug logging enables developers to perform diagnostics on their application to troubleshoot issues.
trackLifecycle Yes Optional. Disables logging.

SDK State

The state property on the Customer Data Platform Mobile SDK shared instance returns json containing current configuration settings, session details, event queue size, and consent information. This information is critical for debugging and troubleshooting purposes.
1CdpSdk.shared.state
State is one of the tools the Customer Data Platform Mobile SDK provides to assist development and troubleshooting. Always inspect the SDK state when debugging to confirm expected configuration. Example Customer Data Platform Mobile SDK state:
1{
2      "name":"cdp",
3      "config": {
4          "screenTrackingEnabled":false,
5          "lifecycleEventTrackingEnabled":false,
6          "appId":"YOUR APP ID",
7          "endpoint":"YOUR ENDPOINT"
8          "sessionDuration":600
9      },
10      "sessionManager": {
11          "sessionId":"SESSION ID"
12      },
13      "eventManager": {
14          "queueSize":2
15      },
16      "consentManager": {
17          "deviceId":"YOUR DEVICE ID",
18          "consent":"opt_in"
19      }
20   }

Consent Management

To help Salesforce customers manage consent and privacy obligations such as the European Union’s General Data Protection Regulation (GDPR), the California Consumer Privacy Act (CCPA), or any internal corporate privacy policy, the Customer Data Platform Mobile SDK offers a managed solution for allowing and restricting collection of event data.

Your mobile application is responsible for presenting the device owner with the choice to opt in or opt out of data collection and for setting the Customer Data Platform Mobile SDK consent property accordingly.

Grant Consent

The Customer Data Platform Mobile SDK can’t transmit events from a mobile device to the Customer Data Platform application until the mobile application has collected user consent for data collection. For quickstart purposes, you can grant consent as shown below.

>
Ask a user to grant consent for data collection when the application is first initialized. Now, when you preview Customer Data Platform Mobile SDK state (CdpSdk.shared.state) consent shows the default value opt_in.
1CdpSdk.shared.consent = Consent.optIn

Consent Parameters

The following table describes Customer Data Platform Mobile SDK configurable settings.

Consent Values Default Description
Consent.optIn No When Consent is set to optIn, events are transmitted to the configured Customer Data Platform endpoint for collection.
Consent.optOut No When Consent is set to optOut, events created by the mobile application are ignored by the Customer Data Platform Mobile SDK. In this scenario, the events are never queued or transmitted off device. If queued events exist when Consent is set to optOut, the Customer Data Platform Mobile SDK deletes them from memory.
Consent.pending Yes Pending is the initial consent value for a newly initialized Customer Data Platform Mobile SDK. In this state, events are collected locally but transmission to Customer Data Platform is restricted. If queued events exist when Consent is changed from pending to optIn, the Customer Data Platform Mobile SDK transmits them to the CDP endpoint.
With the consent information collected from the device user, set Customer Data Platform Mobile SDK consent as follows:
1// grant consent
2          CdpSdk.shared.consent = Consent.optIn
3          
4          // revoke consent
5          CdpSdk.shared.consent = Consent.optOut

Location Tracking

The Customer Data Platform Mobile SDK supports location tracking for all events. Enable this functionality by using the setLocation method on the Customer Data Platform Mobile SDK shared instance to set location coordinates and expires in seconds information.
1// prepare the coordinates
2          let coordinates = Coordinates(latitude: 54.187738, longitude: 15.554440)
3          
4          // set the location coordinates and expiration time
5          CdpSdk.shared.setLocation(coordinates: coordinates, expiresIn: 60)

Given that the SDK has non-expired location coordinates, the location attributes are automatically appended to the event attributes key/value pairs with key names latitude and longitude.

When the expiration interval has been exceeded, the SDK location coordinates are cleared and are no longer attached to events. If you want to prevent location from being attached to events before the coordinates expire, call setLocation and pass nil values as the coordinates.

NOTE: As the application developer, you’re responsible for handling location tracking permission from the end user. You’re responsible for requesting location permission, fetching the location, and ensuring the desired accuracy range.

Event Tracking

The Customer Data Platform Mobile SDK enables collection of granular data about end users’ mobile app interactions through event tracking. An event consists of the event type, and event attributes (optional). The Customer Data Platform Mobile SDK currently supports two event objects, engagement and profile.

Track Events

You can create different types of events, such as an engagement event. To create an event type, instantiate an event and pass in an eventType and (optionally) a collection of attributes.
1let event = Event.engagement(eventType: "CartAbandonment", attributes: 
2          ["sku": "COFFEE-NTR-06", "tag price": 19.99])
To submit an event to the Customer Data Platform application, call the track method on the CdpSdk shared instance.
1CdpSdk.shared.track(event: event)

You can verify which events are being tracked by checking the queueSize under the eventManager section in the Customer Data Platform Mobile SDK state (CdpSdk.shared.state).

Now you’ve successfully configured and initialized the Customer Data Platform Mobile SDK, create an event, and submit that event to the Customer Data Platform application for tracking.

Within the Customer Data Platform Mobile SDK-managed solution, Consent is an enumerated type consisting of three named values: pending, optIn, and optOut. Consent is internally set to “pending” when the SDK is initialized. The mobile application consuming the SDK can update Consent to either optIn or optOut, but can’t revert to pending.

See the following table for details about Customer Data Platform Mobile SDK consent management for customer data collection.

Event Parameters

Parameter Type Description
eventType string Required. Reserved Values: AppFirstLaunch, AppLaunch, AppUpdate, ScreenView. Event Type can’t be empty nor consist of white spaces only.
attributes Dictionary Optional. Event attributes. Some restrictions apply:
  • Key
    • Type: String
    • Required: Yes
    • Reserved Values: userId, deviceId, eventId, sessionId, dateTime, eventType, category
  • Values
    • Supported Types: String, Int, Float, Double, Bool and NSNull
    • If a value is supplied that doesn’t validate as a supported type, the name/value pair is removed from the attributes collection and the action is logged as an Error.
Creating an Event with eventType matching a reserved value isn’t supported and results in an error. Adding a key to the attributes dictionary with a value matching a reserved value results in the key/value pair being dropped. The key/value pair is also dropped if the key/value pairs have an unsupported value type. Example:
1// create engagement event
2          let event = Event.engagement(eventType: "CartAbandonment", attributes: ["sku": "COFFEE-NTR-06", "tag price": 19.99])
3          
4          // track engagement event
5          CdpSdk.shared.track(event: event)
6          
7          // create engagement event (no attributes)
8          let simpleEvent = Event.engagement(eventType: "SortPriceLowToHigh")
9          CdpSdk.shared.track(event: simpleEvent)
10          
11          // create profile event
12          let profileEvent = Event.profile(eventType: "UserUpdate", attributes: ["name": "John"])
13          
14          // track profile event
15          CdpSdk.shared.track(event: profileEvent)