Initialize the SDK
Overview
The OneTrust SDK retrieves and saves all the data needed to display the CMP UI and collect consent for the purposes, vendors and SDKs used by the application. The data returned is determined by the configurations made in the OneTrust tenant/admin console.
Before the SDK can be successfully initialized, ensure that the appropriate SDK data version has been published in the OneTrust tenant/admin console. If it has not been published, there will be no data to retrieve.
For more information on instructions, see Publish Changes.
Start the SDK
This method initializes the SDK and fetches all the data necessary to render the UI and collect consent.
//iOS and tvOS
OTPublishersHeadlessSDK.shared.startSDK(
storageLocation: "cdnLocation",
domainIdentifier: "appID",
languageCode: "languageCode",
params: sdkParams,
loadOffline: false
) { response in
print("status: \(response.status)")
print("result: \(response.responseString ?? "")")
print("error: \(response.error ?? "")")
// Take next action...
}
Parameter | Description | Required |
---|---|---|
storageLocation | CDN location where data needs to be fetched. (Usually, but not always, cdn.cookielaw.org . You can retrieve this from your OneTrust tenant > Mobile App Consent > SDKs > Your App > Instructions. | Yes |
domainIdentifier | The Application ID (retrieved from OneTrust admin console) You can retrieve this from your OneTrust tenant > Mobile App Consent > SDKs > Your App > Instructions. A test and production app ID is available for staging and production. | Yes |
languageCode | 2-digit or 4-digit (in the case of advanced languages) ISO language code used to return content in a specific langauge. Note: Any language code format not listed in the OneTrust environment will be considered as an invalid input. Note: If the languageCode passed by your application is valid, but does not match a language configuration added in your template, the SDK will return content in the default language configured (usually, but not always, English). | Yes |
params | A parameter of type OTSDKParams which contains other optional SDK params like country code, region code, cross device profiles, etc. See below for more details. Pass in nil if not utilized. | No |
loadOffline | Set to true to load Offline Mode data. | No |
completionHandler | The block of code to be triggered once the execution is complete. Also contains a response object that returns the status, error, and response string. More detail below. | Yes |
Response Object
Field | Description | Type |
---|---|---|
status | Status of the data download | Bool |
responseString | Server response of the corresponding API (i.e. banner data or preference center data) | String |
error | Error of the data download, if any | Error |
OTSDKParams
This parameter provides optional additional configurations that can be set by the application while initializing.
Parameter | Description |
---|---|
countryCode | Two-letter ISO 3166-2 country code. This can be used to bypass the automatic geo-ip lookup performed by the SDK. Note: This is used in the initializer for the OTSDKParams object. |
regionCode | Two-letter state code used alongside countryCode. Note: This is used in the initializer for the OTSDKParams object. |
setShouldCreateProfile | When set to "true" , the SDK will create data subject profiles for use with Cross Device Consent. If Cross Device Consent is not in scope, disregard this. For more information on usage, see here. |
setProfileSyncParams | Sets the data subject profile values for Cross Device Consent. If Cross Device Consent is not in scope, disregard this. For more information on usage, see here. |
//iOS and tvOS
let sdkParams = OTSdkParams(countryCode: "US", regionCode: "CA")
Best Practices and Things to Know
- We recommended calling
startSDK
on every app launch to ensure data is fetched regularly- The call will fail if there are internet connectivity issues or an invalid storage URL/domain identifier/language code is passed
- By default, the data from the
responseString
returned as part of theResponseObejct
in the completion handler is from the Banner API. IfsetupUI
is called beforestartSDK
with aUIType
set, the corresponding API data will be returned. For example, if.banner
,.none
or noUIType
is passed, data from the banner API will be returned. If.preferenceCenter
is passed, data from the preference center API will be returned
IMPORTANT
As of 202504.1.0,
startSDK
will no longer download all data for the CMP at once. Instead, data will be downloaded on the fly. For example, Preference Center or Vendor List data will only be fetched if the user tries to navigate to those pages.
Data Caching
After the SDK has successfully fetched any of the API data at least once (e.g. banner data, preference center data, etc.), it caches it locally on the device. If the initialization fails the next time, users will still be able to access the CMP UI and make consent choices.
Cross Device Consent
For more information on Cross Device Consent, see Cross Domain and Cross Device Consent.
Download Banner, Preference Center and Vendors Data (optional)
As of 202504.1.0, only Banner or Preference Center data will be downloaded as part of the startSDK
call.
If setupUI
is called before startSDK
with a UIType
set, then the corresponding UI data will be fetched. For example, if .preferenceCenter
is specified, the only preference center data will be fetched. If no UIType
or a type of .none
is set, then only banner data will be fetched.
If setupUI
is called after startSDK
, only banner data will be fetched as part of the call. If a UIType
of .preferenceCenter
is set and shouldShowBanner
evaluates to true
, then preference center data will subsequently be fetched to render the preference center UI.
If the application wants to retrieve the rest of the data as part of the setup, you can explicitly call the corresponding public methods. See more information on the public methods here.
//iOS and tvOS
//fetch preference center and vendors data
func fetchPCAndVendorsData(completion: @escaping () -> Void) {
OTPublishersHeadlessSDK.shared.fetchPreferenceCenter() { pcDataAsDictionary in
print(pcDataAsDictionary)
OTPublishersHeadlessSDK.shared.fetchVendorsCmpApiData() { vendorsDataAsDictionary in
print(vendorsDataAsDictionary)
completion()
}
}
}
fetchPCAndVendorsData() {
// Take other actions.
}
Passing Custom Geolocation
By default, the OneTrust SDK determines country and region code for a user based on a geo-ip lookup during the startSDK
call to deliver a certain consent experience. If you choose to perform your own geolocation lookup, you can pass in your own countryCode
and regionCode
parameters with OTSDKParams
here.
Retrieving User Location
The SDK returns the location where data was last downloaded and can be used to determine user location. Returns a string:
//iOS and tvOS
let userLocation = OTPublishersHeadlessSDK.shared.getLastDataDownloadedLocation()
print("User Country: \(userLocation.country), User State: \(userLocation.state)")
The SDK returns the location where the user last interacted with the SDK UI and provided consent. Returns a string:
//iOS and tvOS
let consentedLocation = OTPublishersHeadlessSDK.shared.getLastUserConsentedLocation()
print("User Country: \(consentedLocation?.country), User State: \(consentedLocation?.state)")
setOTOfflineData
The offline data mode can be used to initialize the OneTrust SDK without any connection by having the application pass in the CMP data required. The data should be in a JSON format.
If the loadOffline
parameter in startSDK
is passed as false
and the network call to OneTrust fails (e.g. no internet connection, outage, etc.), the SDK will try using the offline data set up using OTPublishersHeadlessSDK.shared.setOTOfflineData(\_:)
. If no data is available, the SDK will fail to initialize.
If the loadOffline
parameter in startSDK
is passed as true
, the SDK will only use the offline data set using OTPublishersHeadlessSDK.shared.setOTOfflineData(\_:)
. If no data is available, the SDK will fail to initialize.
The SDK can only ingest one data set at a time. This means we can only support one geolocation rule, one template, and one language. If your app needs to support multiple experiences, you'll need to store each variation and pass in the appropriate data set accordingly.
Fetching OneTrust Data
There are three separate endpoints to fetch the Banner, Preference Center and Vendor data. See below for tech specs and API reference:
- Fetch the Banner JSON: Get Banner Data
- Fetch the Preference Center JSON: Get Preference Center Data
- Fetch the Vendors JSON: Get IAB and Google Vendors
- This endpoint and data is only needed if you're using the IAB TCF framework
After retrieving all JSON data needed, supply it to the SDK.
//iOS and tvOS
// Helper method for fetching JSON data
func getJSONData(for fileName: String) -> Data? {
guard let path = Bundle.main.path(forResource: fileName, ofType: "json") else {
return nil
}
guard let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
return nil
}
return jsonData
}
func setupOTOfflineData() -> Bool {
let cmpBannerData = getJSONData(for: "OneTrustBannerData")
let cmpPCData = getJSONData(for: "OneTrustPCData")
//only use this if IAB TCF is in scope
let cmpVendorsData = getJSONData(for: "OneTrustVendorsData")
//only use this if Universal Consent is in scope
let cmpUCPData = getJSONData(for: "OneTrustUCPData"), !cmpUCPData.isEmpty else { return false }
let cmpApiFlowData = CmpApiData(
cmpBannerData: cmpBannerData, cmpPreferencesData: cmpPCData,
cmpVendorsData: cmpVendorsData
)
//Logo data
//Note: If any of the logos are not used, pass in nil inside the parameter
let logoData = OTOfflineData.LogoData(bannerLogo: UIImage(named: "filename"),
pcLogo: UIImage(named: "filename"),
ageGateLogo: UIImage(named: "filename"),
attLogo: nil)
let offlineData = OTOfflineData(
cmpApiData: cmpApiFlowData, logoData: logoData
)
OTPublishersHeadlessSDK.shared.setOTOfflineData(offlineData)
return true
}
//setupOTOfflineData() must be called before startSDK()
setupOTOfflineData()
startSDK()
Capture Records of Consent
When a user provides consent, the SDK saves the data locally to the disk. It can also store a record of this consent on OneTrust servers. In order to enable this functionality, enable the Capture Records of Consent toggle in your geolocation rules. This will also allow data to be reflected for Dashboard reporting.
Cross Device Consent
Cross Device Consent is an optional feature. These parameters are not required for initializing the SDK.
If you are implementing the Cross Device Consent functionality, each of these OTProfileSyncParams
parameters are required to be passed to the startSDK() method to sync user profile data with OneTrust servers.
//iOS and tvOS
let profileSyncParam = OTProfileSyncParams()
profileSyncParam.setSyncProfile("true")
profileSyncParam.setSyncProfileAuth("JWT token")
profileSyncParam.setIdentifier("userId")
profileSyncParam.setIdentifierType("identifierType")
profileSyncParam.setSyncGroupId("groupID") //this field is optional and may not be required for your setup
let sdkParams = OTSdkParams(countryCode: "US", regionCode: "CA")
sdkParams.setShouldCreateProfile("true")
sdkParams.setProfileSyncParams(profileSyncParam)
startSDK()
Parameter | Description | Required for Cross Device |
---|---|---|
setSyncProfile | Set to "true" to enable cross device profile syncing. | Yes |
setSyncProfileAuth | Sets the JWT to authenticate your request to fetch user profiles. | Yes |
setIdentifier | Sets the identifier value used to fetch or create a user profile server-side. | Yes |
setIdentifierType | Sets the identifier type for Unified Profile. | No, only when Unified Profile is in use |
setSyncGroupId | Sets the sync group identifier of your consent group. | No |
For more information and best practices on Cross Device Consent, see Cross Domain and Cross Device Consent.
For implementation guidance on moving from an anonymous to known state, see: Override Server Consent.
Updated 1 day ago