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.

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...
}
ParameterDescriptionRequired
storageLocationCDN 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
domainIdentifierThe 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
languageCode2-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 which is not listed in OneTrust environment will be considered as invalid input.

Note: If the languageCode passed by your application is valid, but does not match with a language configuration for your template, then the SDK will return content in the default language configured in OneTrust environment (usually, but not always, English).
Yes
paramsA parameter of type OTSDKParams which contains other optional SDK params like country, region code, cross device profiles, etc. See below for more details. Pass in nil if not utilized.No
loadOfflineSet to true to load Offline Mode data.No
completionHandlerThe block of code that will be triggered once the OneTrust SDK setup is complete. Also contains a response object that returns the status, error, and response string. More detail below. Yes

Response Object

FieldDescriptionType
statusStatus of the data download (successful or not)Bool
responseStringServer response of the corresponding API (i.e. banner data or preference center data)String
errorError of the data download if it was not successfulError

📘

Best Practices and Things to Know

  • We recommended calling startSDKon every app launch to ensure data can be fetched regularly
  • The call will fail if there are internet connectivity issues or an invalid storage URL/domain identifier/language code is passed
  • The data from the responseString returned as part of the ResponseObejct in the completion handler will depend on UIType set in Step 1. If .banner, .none or no UIType 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, startSDKwill 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.

OTSDKParams

This parameter provides optional additional configurations that can be set by the application while setting up the SDK.

ParameterDescription
countryCodeTwo-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.
regionCodeTwo-letter state code used alongside countryCode.
Note: This is used in the initializer for the OTSDKParams object.
setShouldCreateProfileWhen 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.
setProfileSyncParamsSets 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")

👍

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 preference center data will be fetched. If no UIType or a type if .none is set, then banner data will be fetched.

If the application wants to retrieve the rest of the data as well as part of the setup, you can explicitly call the corresponding public methods. More information here.

Sample code: OneTrust SDK performing the SDK UI Presentation

// Step 1
OTPublishersHeadlessSDK.shared.setupUI(appViewController, UIType: .banner)
// Step 2
OTPublishersHeadlessSDK.shared.startSDK(
	storageLocation: "cdn.cookielaw.org", 
	domainIdentifier: "3598fb78-0000-1111-2222-83ee558d6e87", 
	languageCode: "en", 
	params: sdkParams,
	loadOffline: false
) { response in
      print("status: \(response.status)")
      print("result: \(response.responseString ?? "")")
      print("error: \(response.error ?? "")")

      // Step 3 (only supported 202504.1.0 onwards and this is optional)
      fetchPCAndVendorsData() { 
          // Take other actions.
      }
}

func fetchPCAndVendorsData(completion: @escaping () -> Void) {
    OTPublishersHeadlessSDK.shared.fetchPreferenceCenter() { pcDataAsDictionary in
        print(pcDataAsDictionary)
        OTPublishersHeadlessSDK.shared.fetchVendorsCmpApiData() { vendorsDataAsDictionary in 
            print(vendorsDataAsDictionary)
            completion()
        }
    }
}

Sample code: Application taking control over presenting OneTrust UI

OTPublishersHeadlessSDK.shared.startSDK(
	storageLocation: "cdn.cookielaw.org", 
	domainIdentifier: "3598fb78-0000-1111-2222-83ee558d6e87", 
	languageCode: "en", 
	params: sdkParams,
	loadOffline: false
) { response in
      print("status: \(response.status)")
      print("result: \(response.responseString ?? "")")
      print("error: \(response.error ?? "")")
      
      guard let responseString = response.responseString, !responseString.isEmpty,
            response.error == nil else { 
              return "OneTrust Setup failed."
      }
      
      // Step 3 (only supported 202504.1.0 onwards and this is optional)
      fetchPCAndVendorsData() { 
            guard OTPublishersHeadlessSDK.shared.shouldShowBanner() else { return }
            DispatchQueue.main.async {
                OTPublishersHeadlessSDK.shared.setupUI(appViewController)
                OTPublishersHeadlessSDK.shared.showBannerUI()
            }
          // Take other actions.
      }
}

func fetchPCAndVendorsData(completion: @escaping () -> Void) {
    OTPublishersHeadlessSDK.shared.fetchPreferenceCenter() { pcDataAsDictionary in
        print(pcDataAsDictionary)
        OTPublishersHeadlessSDK.shared.fetchVendorsCmpApiData() { vendorsDataAsDictionary in 
            print(vendorsDataAsDictionary)
            completion()
        }
    }
}


Passing Custom Geolocation

The OneTrust SDK, by default, determines a country and region code for a user based on a geo-ip lookup when calling startSDK to deliver a certain template. If you choose to perform your own geolocation lookup, this is supported by using the countryCode and regionCode parameters mentioned above.

Retrieving User Location

The SDK returns the location where data was last downloaded and can be used to determine user location. It returns a string:

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. It returns a string:

let consentedLocation = OTPublishersHeadlessSDK.shared.getLastUserConsentedLocation()
print("User Country: \(consentedLocation?.country), User State: \(consentedLocation?.state)")

Configuring Banner Height

By default, the OneTrust SDK renders the Banner in full screen. You can update this to be Two-thirds, Half, or One-third, depending on your preferences.

📘

OneTrust recommends configuring the banner height from the OneTrust Admin via Templates > Mobile App > Banner > General. This way it can be updated via Publish instead of being hard-coded to the application and require an App Store version update.

For legacy configurations, set the OTBannerHeightRatio parameter to either .two_third, .one_half, or one_third.

setOTOfflineData()

We have introduced an offline data mode which can be used to initialize the OneTrust SDK offline by passing in the json data required for OneTrust SDK setup from the application. This can be achieved by calling the OTOfflineData.setOTOfflineData(_:).

📘

Currently, setupOTOfflineData(_:) will only work for one JSON at a time, which means we can only support one geolocation rule and one language.

If the loadOffline parameter is passed as false and there is no internet connectivity while making the network call to OneTrust, the OneTrust SDK will try using the offline data that is set up using OTPublishersHeadlessSDK.shared.setOTOfflineData(\_:). If no data is available, the SDK will fail to initialize.

If the loadOffline parameter is passed as true, the SDK will only use the offline data set up using OTPublishersHeadlessSDK.shared.setOTOfflineData(\_:). If no data is available, the SDK will fail to initialize.

Setting up OneTrust Data JSON in the application to pass to OneTrust SDK

202504.1.0 onwards

We have separate endpoints to fetch Banner, Preference Center and Vendors.

📘

This change was made as part of CMP API adoption in order to make the processing faster by only downloading and processing the data that the user is navigating to.

Prior to 202504.1.0

We had a single endpoint to fetch all the OneTrust data (Banner, Preference Center, Vendors and Universal Consent Preferences).

In order to retrieve the JSON needed for offline mode, you will have to fetch the data using our mobile data endpoint: Get SDK Configuration.

📘

The endpoints below are only needed if your app is using IAB TCF Framework. If you are not using Google Additional Vendors, disregard the Google endpoint.

After retrieving the JSON specific to your App ID, you will supply this to the SDK.

Sample code snippet

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

// Prior to 202504.1.0
func setupOTOfflineData() -> Bool {
    guard let otData = getJSONData(for: "OneTrustData"), !otData.isEmpty else{ return false} 

    // Set these only for IAB Template, else you can ignore setting the Vendors data.
    let iabData = getJSONData(for: "googleVendorJSONFile")
    let googleData = getJSONData(for: "googleVendorJSONFile") 
    let vendorsData = OTOfflineData.VendorListData(iab: iabData, google: googleData)

    // Setting up the offline data for loading logos in offline mode. 
    // Note: if you are not using any of the below logos, please pass in nil inside the parameter.
    let logoData = OTOfflineData.LogoData(bannerLogo: UIImage(named: "filename"), 
                                          pcLogo: UIImage(named: "filename"), 
                                          ageGateLogo: UIImage(named: "filename"), 
                                          attLogo: nil) 

    // Setting up the offline data required for setting up OT SDK in offline mode.                                   
    let offlineData = OTOfflineData(otData: otData, vendorListData: vendorData, logoData: logoData) 
    OTPublishersHeadlessSDK.shared.setOTOfflineData(offlineData) 
    return true 
} 

// 202504.1.0 onwards
func setupOTOfflineData() -> Bool {
    let cmpBannerData = getJSONData(for: "OneTrustBannerData")
    let cmpPCData = getJSONData(for: "OneTrustPCData")
    
    // If IAB Template, else just dont add this line
    let cmpVendorsData = getJSONData(for: "OneTrustVendorsData")
    
    // If UCP is enabled, else just dont add this line
    let cmpUCPData = getJSONData(for: "OneTrustUCPData"), !cmpUCPData.isEmpty else { return false } 
    
    let cmpApiFlowData = CmpApiData(
        cmpBannerData: cmpBannerData, cmpPreferencesData: cmpPCData,
        cmpVendorsData: cmpVendorsData
    )

    // Setting up the offline data for loading logos in offline mode. 
    // Note: if you are not using any of the below logos, please pass in nil inside the parameter.
    let logoData = OTOfflineData.LogoData(bannerLogo: UIImage(named: "filename"), 
                                          pcLogo: UIImage(named: "filename"), 
                                          ageGateLogo: UIImage(named: "filename"), 
                                          attLogo: nil) 

    // Setting up the offline data required for setting up OT SDK in offline mode.                                   
    let offlineData = OTOfflineData(
        cmpApiData: cmpApiFlowData, logoData: logoData
    ) 
    OTPublishersHeadlessSDK.shared.setOTOfflineData(offlineData) 
    return true 
} 

// Must call setupOTOfflineData() first before startSDK()
setupOTOfflineData()
startSDK()

Capture Records of Consent

When a user gives consent, the SDK automatically saves the consent profile locally to the disk. The user's settings can be reflected in the Preference Center UI without having to make a network call.

Optionally, a user's consent can be saved to OneTrust servers, this feature is known as Capture Records of Consent and is enabled in the Geolocation Rules section of OneTrust Admin, not on the SDK locally.

Enabling Capture Records of Consent is the only way to feed OneTrust Reports and Dashboards, otherwise the consent data is only kept locally on the device.

Creating Data Subject Profiles

The SDK has the ability to display and manage consent for Universal Consent Purposes, and not just Cookie Categories. For this feature to work, the developer needs to call the setShouldCreateProfile(true) method on the SDKParams config object.

If this is not done, then the server will only create Consent Receipts instead of also creating Data Subject Profiles when a user updates their choices.

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 the latest values on OneTrust servers.

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()
ParameterDescriptionRequired for Cross Device
setSyncProfileTells startSDK to attempt Cross Device Consent profile syncing.Yes
setSyncProfileAuthUse this to pass the pre-signed JWT auth token required to perform Cross Device.Yes
setIdentifierSets the identifier value used to create a user profile server-side.Yes
setIdentifierTypeSets the identifier type for Unified Profile.No, only when Unified Profile is in use
setSyncGroupIdSets the sync group identifier.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.