### Initialize SDK with Offline Data - Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt This snippet shows how to initialize the OTPublishers Headless SDK using pre-cached offline data in Swift. It covers creating CMP API and logo data objects from cached files and then setting this offline data before starting the SDK with the `loadOffline` parameter set to true, enabling functionality without network connectivity. ```swift import OTPublishersHeadlessSDK class OfflineConsentManager { func setupOfflineData() { // Create CMP API data from cached files let cmpApiData = OTOfflineData.CmpApiData( cmpBannerData: loadCachedData(named: "banner"), cmpPreferencesData: loadCachedData(named: "preferences"), cmpVendorsData: loadCachedData(named: "vendors") ) // Create logo data let logoData = OTOfflineData.LogoData( bannerLogo: UIImage(named: "banner_logo"), pcLogo: UIImage(named: "pc_logo"), ageGateLogo: UIImage(named: "agegate_logo"), attLogo: UIImage(named: "att_logo") ) // Create offline data object let offlineData = OTOfflineData( cmpApiData: cmpApiData, logoData: logoData ) // Set offline data OTPublishersHeadlessSDK.shared.setOTOfflineData(offlineData) } func initializeWithOfflineData() { setupOfflineData() // Initialize with loadOffline: true OTPublishersHeadlessSDK.shared.startSDK( storageLocation: "cdn.cookielaw.org", domainIdentifier: "your-domain-id", languageCode: "en", params: nil, loadOffline: true ) { response in if response.status { print("SDK initialized with offline data") } } } private func loadCachedData(named: String) -> Data? { guard let url = Bundle.main.url(forResource: named, withExtension: "json") else { return nil } return try? Data(contentsOf: url) } } ``` -------------------------------- ### Get CMP Preference Center Data Dictionary - Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Retrieves the preference center data as a dictionary. This function offers synchronous access to the preference center data, allowing for immediate utilization after it has been fetched. ```swift import OTPublishersHeadlessSDK class CMPDataManager { func getPreferenceCenterDataDictionary() -> [String: Any]? { return OTPublishersHeadlessSDK.shared.getPreferenceCenterData() } } ``` -------------------------------- ### Get CMP Banner Data Dictionary - Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Retrieves the banner data as a dictionary. This method provides synchronous access to the already fetched banner data, useful for immediate use within the application. ```swift import OTPublishersHeadlessSDK class CMPDataManager { func getBannerDataDictionary() -> [String: Any]? { return OTPublishersHeadlessSDK.shared.getBannerData() } } ``` -------------------------------- ### Initialization: startSDK Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Initializes the OneTrust SDK by fetching configuration data from the CDN. This is a mandatory first step for all SDK operations. ```APIDOC ## SDK Initialization ### Description Initializes the OneTrust SDK, downloads consent configuration, and prepares the environment for consent management. ### Method SDK Method (Swift) ### Endpoint OTPublishersHeadlessSDK.shared.startSDK ### Parameters #### Arguments - **storageLocation** (String) - Required - The CDN URL for configuration. - **domainIdentifier** (String) - Required - Unique ID for the OneTrust domain. - **languageCode** (String) - Required - ISO language code for the UI. - **params** (OTSdkParams) - Optional - Geolocation or version overrides. - **loadOffline** (Bool) - Required - Whether to load cached data if offline. ### Request Example OTPublishersHeadlessSDK.shared.startSDK(storageLocation: "cdn.cookielaw.org", domainIdentifier: "5376c4e0-8367-450c-8669-a0d41bed69ac", languageCode: "en", params: nil, loadOffline: false) { response in ... } ### Response #### Success Response - **status** (Bool) - Indicates if initialization succeeded. - **responseString** (String) - Detailed response data. ``` -------------------------------- ### UI Management: setupUI and showBannerUI Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Configures the UI presentation layer and triggers the display of the consent banner. ```APIDOC ## UI Configuration ### Description Configures the SDK UI context and displays the consent banner to the user. ### Method SDK Methods (Swift) ### Endpoint OTPublishersHeadlessSDK.shared.setupUI / showBannerUI ### Parameters #### Arguments - **viewController** (UIViewController) - Required - The parent view controller for UI presentation. - **UIType** (Enum) - Required - The type of UI to initialize (e.g., .banner, .preferenceCenter). ### Request Example OTPublishersHeadlessSDK.shared.setupUI(self, UIType: .banner) OTPublishersHeadlessSDK.shared.showBannerUI() ### Response #### Success Response - **void** - Displays the UI component on the provided view controller. ``` -------------------------------- ### Configure and Display Consent Banner UI Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Configures the UI presentation layer and displays the consent banner. The setupUI method is required to bind the SDK to the current view controller. ```swift import OTPublishersHeadlessSDK import UIKit class ConsentViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() OTPublishersHeadlessSDK.shared.setupUI(self, UIType: .banner) } func showConsentBannerManually() { OTPublishersHeadlessSDK.shared.setupUI(self, UIType: .none) OTPublishersHeadlessSDK.shared.showBannerUI() } func showPreferenceCenterDirectly() { OTPublishersHeadlessSDK.shared.setupUI(self, UIType: .preferenceCenter) } } ``` -------------------------------- ### Initialize OTPublishersHeadlessSDK Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Initializes the OneTrust SDK by fetching configuration data from the CDN. This is a mandatory step that must be performed before invoking other SDK features. ```swift import OTPublishersHeadlessSDK // Initialize SDK with basic parameters OTPublishersHeadlessSDK.shared.startSDK( storageLocation: "cdn.cookielaw.org", domainIdentifier: "5376c4e0-8367-450c-8669-a0d41bed69ac", languageCode: "en", params: nil, loadOffline: false ) { response in if response.status { print("SDK initialized successfully") print("Response: \(response.responseString ?? "")") } else { print("SDK initialization failed: \(response.error?.localizedDescription ?? "Unknown error")") } } // Initialize SDK with custom parameters including geolocation let params = OTSdkParams(countryCode: "US", regionCode: "CA") params.setSDKVersion("202504.1.0") OTPublishersHeadlessSDK.shared.startSDK( storageLocation: "cdn.cookielaw.org", domainIdentifier: "5376c4e0-8367-450c-8669-a0d41bed69ac", languageCode: "en", params: params, loadOffline: false ) { response in if response.status { if OTPublishersHeadlessSDK.shared.shouldShowBanner() { // Show consent UI } } } ``` -------------------------------- ### Initialize and Manage User Profiles for Cross-Device Consent (Swift) Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Initializes the SDK with profile sync parameters to synchronize user consent preferences across devices. It allows for setting user identifiers, sync groups, and tenant IDs. Additionally, it provides functions to switch, rename, delete, and retrieve the current user profile, ensuring consistent consent management. ```swift import OTPublishersHeadlessSDK class ProfileSyncManager { func initializeWithProfileSync(userId: String) { // Create profile sync parameters let profileParams = OTProfileSyncParams() profileParams.setSyncProfile("true") profileParams.setIdentifier(userId) profileParams.setIdentifierType("email") // or "uuid", "custom" profileParams.setSyncGroupId("your-group-id") profileParams.setTenantId("your-tenant-id") // Create SDK params with profile sync let sdkParams = OTSdkParams(countryCode: nil, regionCode: nil) sdkParams.setProfileSyncParams(profileParams) sdkParams.setShouldCreateProfile("true") // Initialize SDK OTPublishersHeadlessSDK.shared.startSDK( storageLocation: "cdn.cookielaw.org", domainIdentifier: "your-domain-id", languageCode: "en", params: sdkParams, loadOffline: false ) { response in if response.status { print("SDK initialized with profile sync") } } } func switchUserProfile(to newUserId: String) { // Switch to different user profile OTPublishersHeadlessSDK.shared.switchProfile(to: newUserId) { error in if let error = error { print("Failed to switch profile: \(error.localizedDescription)") } else { print("Successfully switched to profile: \(newUserId)") } } } func renameProfile(newId: String) { // Rename current profile OTPublishersHeadlessSDK.shared.renameProfile( to: newId, withIdentifierType: "email" ) { success in print("Profile rename \(success ? "succeeded" : "failed")") } } func deleteProfile(profileId: String) { OTPublishersHeadlessSDK.shared.deleteProfile(profileId) { error in if let error = error { print("Failed to delete profile: \(error.localizedDescription)") } else { print("Profile deleted successfully") } } } func getCurrentProfile() -> String { return OTPublishersHeadlessSDK.shared.currentActiveProfile } func isDefaultProfile() -> Bool { return OTPublishersHeadlessSDK.shared.isDefaultProfile() } } ``` -------------------------------- ### Enable and Manage SDK Logging - Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt This snippet demonstrates how to enable various levels of logging, write logs to a file, disable logging, clear SDK data, reset consent, check SDK status, and dismiss the SDK UI using the OTPublishersHeadlessSDK in Swift. It allows developers to troubleshoot SDK behavior and track consent operations. ```swift import OTPublishersHeadlessSDK class SDKDebugger { func enableDebugLogging() { // Available levels: .noLogs, .error, .warning, .info, .debug, .verbose OTPublishersHeadlessSDK.shared.enableOTSDKLog(.verbose) } func enableFileLogging() { // Write logs to file OTPublishersHeadlessSDK.shared.writeLogsToFile(true, debugLog: true) } func disableLogging() { OTPublishersHeadlessSDK.shared.enableOTSDKLog(.noLogs) OTPublishersHeadlessSDK.shared.writeLogsToFile(false, debugLog: false) } func clearAllSDKData() { // Clear all stored OT SDK data OTPublishersHeadlessSDK.shared.clearOTSDKData() } func resetLocalConsent() { // Reset unsaved local consent changes OTPublishersHeadlessSDK.shared.resetUpdatedConsent() } func checkSDKStatus() { // Check if SDK views are currently displayed let isDisplaying = OTPublishersHeadlessSDK.shared.sdkViewsCurrentlyPresented() print("SDK views displayed: \(isDisplaying)") // Check if banner was ever shown let bannerStatus = OTPublishersHeadlessSDK.shared.isBannerShown() // Returns: 1 = shown, 0 = not shown, -1 = not initialized, 2 = profile sync print("Banner shown status: \(bannerStatus)") // Check if banner should be shown let shouldShow = OTPublishersHeadlessSDK.shared.shouldShowBanner() print("Should show banner: \(shouldShow)") } func dismissSDKUI() { OTPublishersHeadlessSDK.shared.dismissUI() } } ``` -------------------------------- ### Check User Consent Status with OTPublishersHeadlessSDK Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Demonstrates how to retrieve user consent status for various entities like categories, purposes, and SDKs using the OTPublishersHeadlessSDK. It helps in determining whether specific functionalities should be enabled based on user consent preferences. ```swift import OTPublishersHeadlessSDK class ConsentChecker { // Category IDs from OneTrust admin console let strictlyNecessary = "C0001" let performance = "C0002" let functional = "C0003" let targeting = "C0004" let socialMedia = "C0005" func checkAnalyticsConsent() -> Bool { // Get saved consent status (last persisted value) let consentStatus = OTPublishersHeadlessSDK.shared.getConsentStatus(forCategory: performance) // Returns: 1 = consent given, 0 = consent not given, -1 = invalid category return consentStatus == 1 } func checkLocalConsent(categoryId: String) -> Bool { // Get local consent (may include unsaved changes) let localStatus = OTPublishersHeadlessSDK.shared.getPurposeConsentLocal(forCustomGroupId: categoryId) return localStatus == 1 } func checkLegitimateInterest(categoryId: String) -> Bool { let legIntStatus = OTPublishersHeadlessSDK.shared.getPurposeLegitInterestLocal(forCustomGroupId: categoryId) return legIntStatus == 1 } func checkSDKConsent(sdkId: String) -> Bool { // Check consent for specific SDK (e.g., Firebase, Mixpanel) let sdkConsent = OTPublishersHeadlessSDK.shared.getConsentStatus(forSDKId: sdkId) return sdkConsent == 1 } func enableAnalyticsIfConsented() { if checkAnalyticsConsent() { // Initialize analytics SDK print("Analytics enabled - user consented") } else { print("Analytics disabled - no consent") } } } ``` -------------------------------- ### Integrate App Tracking Transparency (ATT) with Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt This Swift code integrates with the iOS App Tracking Transparency framework. It provides functions to display the ATT consent UI, show an age gate UI, and check/log the ATT consent status. Dependencies include OTPublishersHeadlessSDK and UIKit. Inputs are a UIViewController for presenting the consent forms. Outputs include callbacks indicating UI dismissal or the granted status of ATT permission. ```swift import OTPublishersHeadlessSDK import UIKit class ATTConsentManager { func showATTConsentUI(from viewController: UIViewController) { // Show IDFA consent UI OTPublishersHeadlessSDK.shared.showConsentUI( for: .idfa, from: viewController ) { print("ATT consent UI dismissed") } } func showAgeGateUI(from viewController: UIViewController) { // Show Age Gate consent UI OTPublishersHeadlessSDK.shared.showConsentUI( for: .ageGate, from: viewController ) { print("Age gate UI dismissed") } } func checkAndLogATTConsent() { // Check and log ATT consent OTPublishersHeadlessSDK.shared.checkAndLogConsent(for: .idfa) { granted in print("ATT permission granted: \(granted)") } } func getAgeGateStatus() -> Int { // Returns: 1 = Yes, 0 = No, -1 = Not interacted return OTPublishersHeadlessSDK.shared.getAgeGatePromptValue() } } ``` -------------------------------- ### Manage Vendor Consent Information Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Provides methods to retrieve vendor lists based on mode (IAB, Google, General), fetch specific vendor details, and count vendors by category. It demonstrates how to iterate through vendor collections to access consent and legitimate interest statuses. ```swift import OTPublishersHeadlessSDK class VendorManager { func getAllVendors(mode: VendorListMode) -> [String: any VendorsInfoProtocol]? { return OTPublishersHeadlessSDK.shared.getAllVendors(mode: mode) } func getVendorDetails(vendorId: String, mode: VendorListMode) -> (any VendorsInfoProtocol)? { return OTPublishersHeadlessSDK.shared.getVendorDetails(vendorId: vendorId, for: mode) } func displayVendorInfo() { if let iabVendors = getAllVendors(mode: .iab) { for (vendorId, vendor) in iabVendors { print("Vendor ID: \(vendorId)") print("Name: \(vendor.name ?? "Unknown")") print("Consent: \(vendor.getLatestConsent() ?? -1)") print("Legit Interest: \(vendor.getLatestLegIntStatus() ?? -1)") } } if let googleVendors = getAllVendors(mode: .google) { for (vendorId, vendor) in googleVendors { print("Google Vendor: \(vendor.name ?? vendorId)") } } if let generalVendors = getAllVendors(mode: .general) { for (vendorId, vendor) in generalVendors { print("General Vendor: \(vendor.name ?? vendorId)") } } } func getVendorCount(categoryId: String) -> Int { return OTPublishersHeadlessSDK.shared.getVendorCount(forCategory: categoryId) } func getVendorListUIStyling() -> VendorListUIData? { return OTPublishersHeadlessSDK.shared.getVendorsListUIStylingData() } } ``` -------------------------------- ### Preference Center: showPreferenceCenterUI Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Displays the preference center UI, allowing users to granularly manage their consent categories. ```APIDOC ## Preference Center ### Description Displays the detailed preference center for users to manage consent categories. ### Method SDK Method (Swift) ### Endpoint OTPublishersHeadlessSDK.shared.showPreferenceCenterUI ### Parameters #### Arguments - **None** ### Request Example OTPublishersHeadlessSDK.shared.showPreferenceCenterUI() ### Response #### Success Response - **void** - Opens the preference center modal. ``` -------------------------------- ### Manage Universal Consent Purposes (UCP) with Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt APIs to manage consent for custom purposes and preferences configured in the OneTrust admin console. These functions allow retrieving and updating consent for specific UCPs and custom preferences, as well as displaying the UCP UI. Dependencies include the OTPublishersHeadlessSDK. Inputs are purpose IDs, preference IDs, option IDs, and a boolean for granting consent. Outputs are integer status codes for consent retrieval. ```swift import OTPublishersHeadlessSDK class UniversalConsentManager { func getUCPurposeConsent(purposeId: String) -> Int { // Get consent for a UC purpose // Returns: 1 = consent given, 0 = not given, -1 = invalid ID return OTPublishersHeadlessSDK.shared.getUCPurposeConsent(purposeID: purposeId) } func updateUCPurposeConsent(purposeId: String, granted: Bool) { OTPublishersHeadlessSDK.shared.updateUCPurposeConsent( purposeId: purposeId, withConsent: granted ) } func getCustomPreferenceConsent( optionId: String, preferenceId: String, purposeId: String ) -> Int { // Get consent for specific custom preference option return OTPublishersHeadlessSDK.shared.getUCPurposeConsent( customPreferenceOptionID: optionId, customPreferenceID: preferenceId, purposeID: purposeId ) } func updateCustomPreferenceConsent( optionId: String, preferenceId: String, purposeId: String, granted: Bool ) { OTPublishersHeadlessSDK.shared.updateUCPurposeConsent( cpOptionId: optionId, cpId: preferenceId, purposeId: purposeId, withConsent: granted ) } func showUCPurposesUI(from viewController: UIViewController) { OTPublishersHeadlessSDK.shared.showConsentPurposesUI(viewController) } } ``` -------------------------------- ### Customize SDK UI Appearance Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Implements the UIConfigurator protocol to apply custom styling, define configuration file paths, and control UI behavior such as dark mode and consent confirmation journeys. ```swift import OTPublishersHeadlessSDK class CustomUIConfigurator: NSObject, UIConfigurator { func setupConfigurator() { OTPublishersHeadlessSDK.shared.uiConfigurator = self } func shouldUseCustomUIConfig() -> Bool { return true } func customUIConfigFilePath() -> String? { return Bundle.main.path(forResource: "CustomOTSDK-UIConfig", ofType: "plist") } func getVendorListJourney() -> VendorListJourneyType { return .showConfirmMyChoices } @available(iOS 13.0, *) func shouldEnableDarkMode() -> Bool { return false } } ``` -------------------------------- ### Inject Consent JavaScript into WebView with Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt This code snippet demonstrates how to inject JavaScript into a WKWebView to synchronize consent status between native and web contexts. It uses the `getOTConsentJSForWebView` method from the SDK to obtain the necessary JavaScript code. The primary dependency is the OTPublishersHeadlessSDK and WKWebView. The function takes no direct inputs but relies on the SDK's current consent state. The output is the execution of JavaScript within the WebView. ```swift import OTPublishersHeadlessSDK import WebKit class ConsentWebViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() let config = WKWebViewConfiguration() webView = WKWebView(frame: view.bounds, configuration: config) webView.navigationDelegate = self view.addSubview(webView) loadWebContent() } func loadWebContent() { guard let url = URL(string: "https://your-website.com") else { return } webView.load(URLRequest(url: url)) } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { injectConsentToWebView() } func injectConsentToWebView() { // Get consent JavaScript string guard let consentJS = OTPublishersHeadlessSDK.shared.getOTConsentJSForWebView() else { print("Consent JS not available") return } // Inject into WebView webView.evaluateJavaScript(consentJS) { result, error in if let error = error { print("Failed to inject consent: \(error.localizedDescription)") } else { print("Consent injected successfully") } } } } ``` -------------------------------- ### UI Customization API Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt APIs to customize the appearance and behavior of the SDK's user interface. ```APIDOC ## UI Customization The `UIConfigurator` protocol allows customization of SDK UI appearance. Implement this protocol to use custom styling and control UI behavior. ### `setupConfigurator` **Description**: Sets the current object as the UI configurator for the SDK. ### `shouldUseCustomUIConfig` **Description**: Determines whether to use custom UI configuration. **Returns**: `true` to use custom UI configuration, `false` otherwise. ### `customUIConfigFilePath` **Description**: Provides the file path to the custom UI configuration plist file. **Returns**: Optional String representing the file path, or nil. ### `getVendorListJourney` **Description**: Defines the user journey for the vendor list. **Returns**: `VendorListJourneyType` enum value. Possible values are `.showConfirmMyChoices` (show confirm button) or `.hideConfirmMyChoices` (save locally only). ### `shouldEnableDarkMode` **Description**: Overrides the device's dark mode setting for the SDK. **Returns**: `true` to force dark mode, `false` to force light mode. Requires iOS 13.0 or later. ``` -------------------------------- ### Fetch CMP Preferences Data - Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Asynchronously fetches preferences data from the CMP API. This function is designed to retrieve user preferences, ensuring the data is loaded before any related UI is presented. It logs the fetched data or an error message. ```swift import OTPublishersHeadlessSDK class CMPDataManager { func fetchPreferencesData() { OTPublishersHeadlessSDK.shared.fetchPreferencesCmpApiData { data in if let prefsData = data { print("Preferences data fetched: \(prefsData)") } else { print("Failed to fetch preferences data") } } } } ``` -------------------------------- ### Update User Consent Programmatically with OTPublishersHeadlessSDK Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Provides methods for programmatically updating user consent for categories, SDKs, and vendors using the OTPublishersHeadlessSDK. This is useful for custom preference UIs or automated consent management workflows. ```swift import OTPublishersHeadlessSDK class ConsentManager { func updateCategoryConsent(categoryId: String, granted: Bool) { // Update consent for a specific category OTPublishersHeadlessSDK.shared.updatePurposeConsent( forGroup: categoryId, consentValue: granted, updateHierarchy: true // Also update parent/child categories ) } func updateSDKConsent(sdkId: String, granted: Bool) { // Update consent for a specific SDK OTPublishersHeadlessSDK.shared.updateSDKConsent( for: sdkId, consentValue: granted, updateHierarchy: true ) } func updateAllSDKsConsent(granted: Bool) { // Update all SDKs at once OTPublishersHeadlessSDK.shared.updateAllSDKsConsentLocal( consentValue: granted, updateHierarchy: true ) } func updateVendorConsent(vendorId: String, granted: Bool, mode: VendorListMode = .iab) { // Update consent for a specific vendor OTPublishersHeadlessSDK.shared.updateVendorConsent( vendorID: vendorId, consentStatus: granted, for: mode ) } func updateVendorLegitimateInterest(vendorId: String, granted: Bool) { // Update legitimate interest for IAB vendor OTPublishersHeadlessSDK.shared.updateVendorLegitInterest( vendorID: vendorId, legIntStatus: granted, for: .iab ) } func updateAllVendors(granted: Bool, mode: VendorListMode) { // Update all vendors at once OTPublishersHeadlessSDK.shared.updateAllVendorsConsentLocal(granted, for: mode) } func updateLegitimateInterest(categoryId: String, granted: Bool) { // Update legitimate interest for a category OTPublishersHeadlessSDK.shared.updatePurposeLegitInterest( forGroup: categoryId, legIntValue: granted ) } } ``` -------------------------------- ### Fetch CMP Vendors Data - Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Asynchronously fetches vendor data from the CMP API. This method is crucial for obtaining information about available vendors, ensuring data is ready before rendering related UI components. It provides feedback on the success or failure of the data fetch. ```swift import OTPublishersHeadlessSDK class CMPDataManager { func fetchVendorsData() { OTPublishersHeadlessSDK.shared.fetchVendorsCmpApiData { data in if let vendorsData = data { print("Vendors data fetched: \(vendorsData)") } else { print("Failed to fetch vendors data") } } } } ``` -------------------------------- ### Implement Consent Event Listeners in Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt The OTEventListener protocol allows developers to hook into the lifecycle of consent UI components. By implementing this protocol, you can respond to banner visibility, preference center interactions, and specific consent status changes. ```swift import OTPublishersHeadlessSDK class ConsentEventHandler: NSObject, OTEventListener { func setupEventListener() { OTPublishersHeadlessSDK.shared.addEventListener(self) } func onShowBanner() { print("Consent banner is now visible") } func onPreferenceCenterPurposeConsentChanged(purposeId: String, consentStatus: Int8) { print("Purpose \(purposeId) consent changed to: \(consentStatus)") } func allSDKViewsDismissed(interactionType: ConsentInteractionType) { print("All SDK views dismissed with interaction: \(interactionType)") } } ``` -------------------------------- ### App Tracking Transparency (ATT) API Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Manages iOS-specific consent flows including App Tracking Transparency (IDFA) and Age Gate prompts. ```APIDOC ## POST /att/consent ### Description Triggers the native UI for IDFA or Age Gate consent collection. ### Method POST ### Parameters #### Request Body - **type** (Enum) - Required - The type of consent UI to show (.idfa or .ageGate). ## GET /att/status ### Description Checks the current status of the Age Gate or ATT consent. ### Method GET ### Response #### Success Response (200) - **status** (Int) - Returns 1 for granted/yes, 0 for denied/no, -1 for no interaction. ``` -------------------------------- ### Display Preference Center UI Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Provides methods to display the preference center or universal consent purposes UI, allowing users to manage their privacy settings. ```swift import OTPublishersHeadlessSDK import UIKit class SettingsViewController: UIViewController { @IBAction func privacySettingsTapped(_ sender: UIButton) { OTPublishersHeadlessSDK.shared.setupUI(self, UIType: .none) OTPublishersHeadlessSDK.shared.showPreferenceCenterUI() } func showConsentPurposesUI() { OTPublishersHeadlessSDK.shared.showConsentPurposesUI(self) } } ``` -------------------------------- ### Fetch CMP Banner Data - Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Asynchronously fetches banner data from the CMP API. This method is useful when you need to ensure banner data is available before displaying UI elements. It handles success and failure cases by printing messages. ```swift import OTPublishersHeadlessSDK class CMPDataManager { func fetchBannerData() { OTPublishersHeadlessSDK.shared.fetchBannerCmpApiData { data in if let bannerData = data { print("Banner data fetched: \(bannerData)") } else { print("Failed to fetch banner data") } } } } ``` -------------------------------- ### WebView Consent Injection API Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Provides a mechanism to synchronize native consent settings with web-based content via JavaScript injection. ```APIDOC ## GET /webview/consent-js ### Description Generates a JavaScript string containing the current user consent state, intended for injection into a WKWebView to ensure cross-context consent consistency. ### Method GET ### Response #### Success Response (200) - **jsString** (String) - The JavaScript code to be evaluated in the WebView context. ``` -------------------------------- ### Vendor Management API Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt APIs to retrieve and manage vendor consent information for IAB, Google, and general vendors. ```APIDOC ## Vendor Management These APIs allow you to retrieve and manage vendor consent information for IAB, Google, and general vendors configured in your OneTrust template. ### `getAllVendors` **Description**: Retrieves all vendors based on the specified mode. **Parameters**: - `mode` (VendorListMode) - Required - Specifies the type of vendors to retrieve (e.g., .iab, .google, .general). **Returns**: A dictionary of vendor IDs to vendor information, or nil if an error occurs. ### `getVendorDetails` **Description**: Retrieves details for a specific vendor. **Parameters**: - `vendorId` (String) - Required - The ID of the vendor to retrieve. - `mode` (VendorListMode) - Required - Specifies the type of vendors to retrieve. **Returns**: Vendor information object conforming to `VendorsInfoProtocol`, or nil if the vendor is not found. ### `getVendorCount` **Description**: Retrieves the count of vendors within a specific category. **Parameters**: - `categoryId` (String) - Required - The ID of the category. **Returns**: The number of vendors in the specified category. ### `getVendorListUIStyling` **Description**: Retrieves the UI styling data for the vendor list. **Returns**: `VendorListUIData` object containing styling information, or nil. ``` -------------------------------- ### Fetch CMP UC Purposes Data - Swift Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Asynchronously fetches UC (User Consent) purposes data from the CMP API. This function is essential for retrieving specific consent purposes, ensuring the data is loaded prior to UI presentation. It logs the fetched data or indicates a failure. ```swift import OTPublishersHeadlessSDK class CMPDataManager { func fetchUCPurposesData() { OTPublishersHeadlessSDK.shared.fetchUCPurposesCmpApiData { data in if let ucData = data { print("UC Purposes data fetched: \(ucData)") } else { print("Failed to fetch UC Purposes data") } } } } ``` -------------------------------- ### Read IAB TCF 2.0 Consent Values (Swift) Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Retrieves various IAB TCF 2.0 consent string values from UserDefaults using predefined keys. These values are crucial for GDPR compliance and ad serving integrations. It reads TC String, GDPR applicability, purpose and vendor consents, legitimate interests, special features opt-ins, and CMP information. ```swift import OTPublishersHeadlessSDK class IABConsentReader { func readIABTCFValues() { let defaults = UserDefaults.standard // Read TC String (the encoded consent string) if let tcString = defaults.string(forKey: OTIABTCFKeys.iabTcf2TCString) { print("TC String: \(tcString)") } // Check if GDPR applies if let gdprApplies = defaults.object(forKey: OTIABTCFKeys.iabTcf2GdprApplies) as? Int { print("GDPR Applies: \(gdprApplies == 1)") } // Read purpose consents (binary string) if let purposeConsents = defaults.string(forKey: OTIABTCFKeys.iabTcf2PurposeConsents) { print("Purpose Consents: \(purposeConsents)") } // Read vendor consents (binary string) if let vendorConsents = defaults.string(forKey: OTIABTCFKeys.iabTcf2VendorConsents) { print("Vendor Consents: \(vendorConsents)") } // Read vendor legitimate interests if let vendorLegInt = defaults.string(forKey: OTIABTCFKeys.iabTcf2VendorLegitimateInterests) { print("Vendor Legitimate Interests: \(vendorLegInt)") } // Read purpose legitimate interests if let purposeLegInt = defaults.string(forKey: OTIABTCFKeys.iabTcf2PurposeLegitimateInterests) { print("Purpose Legitimate Interests: \(purposeLegInt)") } // Read special features opt-ins if let specialFeatures = defaults.string(forKey: OTIABTCFKeys.iabTcf2SpecialFeaturesOptIns) { print("Special Features Opt-ins: \(specialFeatures)") } // CMP information if let cmpSdkId = defaults.string(forKey: OTIABTCFKeys.iabTcf2CmpSdkId) { print("CMP SDK ID: \(cmpSdkId)") } if let cmpVersion = defaults.string(forKey: OTIABTCFKeys.iabTcf2CmpSdkVersion) { print("CMP Version: \(cmpVersion)") } // Google Additional Consent if let addtlConsent = defaults.string(forKey: OTIABTCFKeys.iabTcf2AddtlConsent) { print("Additional Consent: \(addtlConsent)") } } } ``` -------------------------------- ### Save Consent Choices with OneTrust Headless SDK Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt The saveConsent method is used to persist user consent updates to the OneTrust server. It accepts various interaction types to categorize the user's action, such as accepting all cookies or confirming preference center choices. ```swift import OTPublishersHeadlessSDK class ConsentPersistence { func acceptAllConsent() { OTPublishersHeadlessSDK.shared.saveConsent(type: .bannerAllowAll) { print("All consent accepted and saved") } } func rejectAllConsent() { OTPublishersHeadlessSDK.shared.saveConsent(type: .bannerRejectAll) { print("All consent rejected and saved") } } func savePreferenceCenterChoices() { OTPublishersHeadlessSDK.shared.saveConsent(type: .preferenceCenterConfirm) { print("Preference center choices saved") } } func saveVendorListChoices() { OTPublishersHeadlessSDK.shared.saveConsent(type: .vendorListConfirm) { print("Vendor list choices saved") } } } ``` -------------------------------- ### Universal Consent Purposes (UCP) API Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Methods for retrieving and updating consent status for custom purposes and specific preference options defined in the OneTrust console. ```APIDOC ## GET /uc/purpose ### Description Retrieves the current consent status for a specific Universal Consent purpose. ### Method GET ### Parameters #### Query Parameters - **purposeId** (String) - Required - The unique identifier for the consent purpose. ### Response #### Success Response (200) - **status** (Int) - 1 = consent given, 0 = not given, -1 = invalid ID. ## POST /uc/purpose ### Description Updates the consent status for a specific Universal Consent purpose. ### Method POST ### Request Body - **purposeId** (String) - Required - The unique identifier for the consent purpose. - **granted** (Bool) - Required - The new consent status. ``` -------------------------------- ### Retrieve Geolocation Data Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt Retrieves the geographical location where SDK data was downloaded and where the user last provided consent. This is essential for compliance reporting and auditing user consent history. ```swift import OTPublishersHeadlessSDK class GeolocationManager { func getDataDownloadLocation() -> OTGeolocationModel { return OTPublishersHeadlessSDK.shared.getLastDataDownloadedLocation() } func getUserConsentLocation() -> OTGeolocationModel? { return OTPublishersHeadlessSDK.shared.getLastUserConsentedLocation() } func displayLocationInfo() { let downloadLocation = getDataDownloadLocation() print("Data downloaded in: \(downloadLocation.country), \(downloadLocation.state)") if let consentLocation = getUserConsentLocation() { print("User consented in: \(consentLocation.country), \(consentLocation.state)") } else { print("User has not provided consent yet") } } } ``` -------------------------------- ### Geolocation API Source: https://context7.com/zentrust/otpublishersheadlesssdk/llms.txt APIs to retrieve geolocation information for consent data. ```APIDOC ## Geolocation These APIs retrieve geolocation information about where consent data was downloaded and where the user last provided consent, useful for compliance reporting. ### `getDataDownloadLocation` **Description**: Gets the location where the SDK data was last downloaded. **Returns**: `OTGeolocationModel` object containing the download location details. ### `getUserConsentLocation` **Description**: Gets the location where the user last provided consent. Returns nil if the user has not yet consented. **Returns**: `OTGeolocationModel` object containing the consent location, or nil. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.