Cómo integrar el SDK de UniConsent CMP para iOS con aplicaciones móviles

UniConsent CMP es un paquete para gestionar el consentimiento GDPR IAB TCF 2.3 en iOS. Puede encontrar una aplicación de demostración integrada con UniConsent CMP en el directorio "UniConsentDemo".

Requisitos previos

  • Plan UniConsent CMP con soporte para aplicaciones móviles
  • iOS >= 15.0
  • Paquete del SDK de UniConsent CMP (solicitar al soporte)

Primeros pasos

Agregue UniConsent.xcframework a su proyecto. En General > Frameworks, Libraries, and Embedded Content de su target, configure UniConsent.xcframework como Embed & Sign.

Personalizar la interfaz de consentimiento

Antes de integrar el SDK, personalice la apariencia del banner de consentimiento en el panel de control de UniConsent para que coincida con su marca y optimice las tasas de consentimiento.

Paso 1: Estilo de marca en el panel de control

Vaya a Projects → Select your Project → Settings → Step 5: UI & Style Settings para configurar:

  • Main Button Colour — Establezca el color del botón de acción principal para que coincida con su marca
  • Main Button Text Colour — Ajuste el color del texto del botón principal para facilitar la lectura
  • Background Colour — Establezca el color de fondo del banner para que se integre con su aplicación
  • Text Colour — Asegúrese de que el texto del cuerpo tenga el contraste adecuado

Paso 2: Estilo avanzado con CSS personalizado (opcional)

Para un control más preciso, agregue CSS personalizado en el campo CSS Content en el Paso 5. Esto se recomienda para que el banner se sienta nativo en su aplicación y logre la mejor tasa de consentimiento:

/* Example: Style the accept button to match your brand */
.unic-btn-accept {
  background-color: #4CAF50;
  border-radius: 8px;
  font-weight: 600;
}

/* Example: Adjust banner font */
.unic-banner {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* Example: Make the reject button less prominent */
.unic-btn-reject {
  background-color: transparent;
  border: 1px solid #ccc;
  color: #666;
}

Consejo: Una interfaz de consentimiento bien personalizada que se sienta nativa en su aplicación generalmente logra tasas de consentimiento más altas. Los usuarios tienden a interactuar de manera más positiva con un banner que coincide con la apariencia que esperan.

Uso

Para usar UniConsent CMP en su aplicación, siga estos pasos:

Inicialice el CMP con un App ID proporcionado por su gestor de cuenta:

import UniConsent

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Init CMP with appId
    UniConsentCMP.shared.initialize(apiId: "YOUR_APP_ID_CHANGE_THIS")
    return true
}

Mostrar la interfaz del CMP:

// Display CMP as full-screen modal (default)
UniConsentCMP.shared.setUIStage(.GDPRFirstScreen)
UniConsentCMP.shared.launchCMP(rootVC: self)

// Display CMP as a modal bottom sheet
UniConsentCMP.shared.launchCMP(rootVC: self, displayMode: .modalSheet)

// Display CMP as a center dialog
UniConsentCMP.shared.launchCMP(rootVC: self, displayMode: .dialog)

Modos de visualización disponibles (CMPDisplayMode):

  • .fullScreen — Presentación modal a pantalla completa (predeterminado)
  • .modalSheet — Hoja inferior con controlador de arrastre (iOS 15+)
  • .dialog — Diálogo centrado con fondo atenuado

Manejador de eventos

Escuche los eventos del ciclo de vida del SDK con CMPEventHandler. Esta es la forma recomendada de saber cuándo el SDK ha terminado de inicializarse, cuándo se muestra la interfaz y cuándo se cierra.

Eventos disponibles (CMPEventType):

  • .sdkInit — Inicio de la inicialización del SDK
  • .ready — Inicialización del SDK completada (GEO, configuración y proveedores cargados)
  • .uiDisplay — La interfaz de consentimiento se muestra
  • .uiClose — La interfaz de consentimiento se cierra

Suscríbase a los eventos antes de llamar a initialize() para recibir todos los eventos:

import UniConsent

@main
class AppDelegate: UIResponder, UIApplicationDelegate, CMPEventHandler {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UniConsentCMP.shared.subscribe(self)
        UniConsentCMP.shared.initialize(apiId: "YOUR_APP_ID")
        return true
    }

    func handle(event: CMPEvent) {
        switch event.type {
        case .ready:
            // SDK is ready — check consent and launch CMP if needed
            if UniConsentCMP.shared.shouldRequestConsent() {
                // launch CMP from your root view controller
            }
        case .uiClose:
            // User finished interacting with consent UI
            print("TC String:", UniConsentCMP.shared.getTCString())
        default:
            break
        }
    }
}

También puede suscribirse desde un view controller:

class ViewController: UIViewController, CMPEventHandler {

    override func viewDidLoad() {
        super.viewDidLoad()
        UniConsentCMP.shared.subscribe(self)
    }

    func handle(event: CMPEvent) {
        switch event.type {
        case .uiDisplay:
            print("CMP UI is now visible")
        case .uiClose:
            print("Consent given, vendor 1 allowed:", UniConsentCMP.shared.isAllowVendorById(vendorId: 1))
        default:
            break
        }
    }
}

Para cancelar la suscripción:

UniConsentCMP.shared.unsubscribe(self)

CMPUIDelegate (legacy)

También puede escuchar el cierre del consentimiento con CMPUIDelegate:

class ViewController: UIViewController, CMPUIDelegate {

    func showCMP() {
        UniConsentCMP.shared.view.delegate = self
        UniConsentCMP.shared.setUIStage(.GDPRFirstScreen)
        UniConsentCMP.shared.launchCMP(rootVC: self, displayMode: .modalSheet)
    }

    func onDismiss() {
        // Called when the user closes the consent UI
        print("TC String:", UniConsentCMP.shared.getTCString())
    }
}

Verificar automáticamente si el consentimiento ha expirado cuando se actualiza la lista de proveedores:

// Automatic check if consent is expired when vendorList updates
if UniConsentCMP.shared.shouldRequestConsent() {
    UniConsentCMP.shared.launchCMP(rootVC: self)
}

Obtener el tcString si es necesario:

// Get tcString if required
UniConsentCMP.shared.getTCString()

Leer el estado del consentimiento:

// Check consent for a specific IAB purpose
UniConsentCMP.shared.isAllowPurposeById(purposeId: 1)

// Check consent for a specific IAB vendor
UniConsentCMP.shared.isAllowVendorById(vendorId: 1)

// Get all allowed purpose/vendor IDs
UniConsentCMP.shared.getAllowedPurposeIds()
UniConsentCMP.shared.getAllowedVendorIds()

// Check if GDPR applies
UniConsentCMP.shared.gdprApplies

// Check if any consent has been given
UniConsentCMP.shared.isConsentGiven()

Restablecer el estado del consentimiento si es necesario:

// Reset consent status if required
UniConsentCMP.shared.clearConsentData()

Sincronizar el consentimiento con WebView

Si su aplicación abre un WKWebView que carga una página web con la etiqueta UniConsent CMP, puede pasar el estado de consentimiento nativo para que la etiqueta CMP reconozca el consentimiento existente y no muestre el banner nuevamente.

Llame a syncConsent(to:) antes de cargar la página web:

import WebKit
import UniConsent

let webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())

// Inject native consent before page load
UniConsentCMP.shared.syncConsent(to: webView)

// Then load your web page
webView.load(URLRequest(url: URL(string: "https://example.com")!))

Objective-C

// Initialize with event handler
@interface AppDelegate () <CMPEventHandler>
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[UniConsentCMP shared] subscribe:self];
    [[UniConsentCMP shared] initializeWithApiId:@"YOUR_APP_ID"];
    return YES;
}

- (void)handleWithEvent:(CMPEvent *)event {
    switch (event.type) {
        case CMPEventTypeReady:
            NSLog(@"CMP ready");
            break;
        case CMPEventTypeUiClose:
            NSLog(@"TC String: %@", [[UniConsentCMP shared] getTCString]);
            break;
        default:
            break;
    }
}

@end

// Display CMP (full screen by default)
[UniConsentCMP.shared launchCMPWithRootVC:self];

// Display CMP with a specific display mode
// Use CMPDisplayModeFullScreen, CMPDisplayModeModalSheet, or CMPDisplayModeDialog
[UniConsentCMP.shared launchCMPWithRootVC:self displayMode:CMPDisplayModeModalSheet];

Configurar los valores predeterminados de estado de consentimiento KV:

<key>FIREBASE_ANALYTICS_COLLECTION_ENABLED</key> <false/>
<key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_ANALYTICS_STORAGE</key> <false/>
<key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_STORAGE</key> <false/>
<key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_USER_DATA</key> <false/>
<key>GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS</key> <false/>

Controlar la analítica basándose en los indicadores de consentimiento:

// SDK Version <= 25.6.1
public func onDismiss() {

    if(UniConsentCMP.shared.isAllowPurposeById(purposeId: 1)) {
        Analytics.setConsent([
          .analyticsStorage: .granted,
          .adStorage: .granted,
          .adUserData: .granted,
          .adPersonalization: .granted,
        ])
        Analytics.setAnalyticsCollectionEnabled(true);
    } else {
        Analytics.setConsent([
          .analyticsStorage: .denied,
          .adStorage: .denied,
          .adUserData: .denied,
          .adPersonalization: .denied,
        ])
        Analytics.setAnalyticsCollectionEnabled(false);
    }

    // other logics such as send analytics events
}

Más información en Set up consent mode for apps

Notas

  1. Los usuarios deben tener la posibilidad de acceder a un botón o enlace de "Configuración de privacidad" en la sección de ajustes de su aplicación para abrir la interfaz del CMP.
  2. Puede utilizar la función shouldRequestConsent() para verificar si debe solicitar un nuevo consentimiento según el estado. Muestre la interfaz del CMP cuando sea necesario al abrir la aplicación.
  3. A partir de la versión 25.6.1 del SDK, ya no necesita enviar manualmente las opciones de consentimiento para FirebaseAnalytics o ciertos SDKs AAP compatibles, ya que el SDK los gestiona automáticamente. Para más información, consulte What is Google AAP and Google MMP for Mobile Apps?.