Comment intégrer le SDK CMP UniConsent pour iOS dans les applications mobiles

UniConsent CMP est un package pour la gestion du consentement GDPR IAB TCF 2.3 sur iOS. Vous trouverez une application de démonstration intégrée avec UniConsent CMP dans le répertoire « UniConsentDemo ».

Prérequis

  • Plan UniConsent CMP avec support des applications mobiles
  • iOS >= 15.0
  • Package SDK CMP UniConsent (à demander au support)

Pour commencer

Ajoutez UniConsent.xcframework à votre projet. Dans les paramètres de votre cible sous General > Frameworks, Libraries, and Embedded Content, définissez UniConsent.xcframework sur Embed & Sign.

Personnaliser l'interface de consentement

Avant d'intégrer le SDK, personnalisez l'apparence de la bannière de consentement dans le tableau de bord UniConsent pour qu'elle corresponde à votre marque et optimise les taux de consentement.

Étape 1 : Style de marque dans le tableau de bord

Accédez à Projects → Select your Project → Settings → Step 5: UI & Style Settings pour configurer :

  • Main Button Colour — Définissez la couleur du bouton d'action principal pour correspondre à votre marque
  • Main Button Text Colour — Ajustez la couleur du texte sur le bouton principal pour la lisibilité
  • Background Colour — Définissez la couleur de fond de la bannière pour s'harmoniser avec votre application
  • Text Colour — Assurez-vous que le texte du corps a un contraste approprié

Étape 2 : Style avancé avec CSS personnalisé (optionnel)

Pour un contrôle plus précis, ajoutez du CSS personnalisé dans le champ CSS Content sous l'étape 5. Ceci est recommandé pour que la bannière s'intègre nativement à votre application et obtienne le meilleur taux de consentement :

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

Astuce : Une interface de consentement bien adaptée à votre marque et qui semble native à votre application obtient généralement de meilleurs taux de consentement. Les utilisateurs sont plus enclins à réagir positivement face à une bannière qui correspond à l'apparence et au style qu'ils attendent.

Utilisation

Pour utiliser UniConsent CMP dans votre application, suivez ces étapes :

Initialisez la CMP avec un App ID fourni par votre gestionnaire de compte :

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
}

Affichez l'interface 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)

Modes d'affichage disponibles (CMPDisplayMode) :

  • .fullScreen — Présentation modale plein écran (par défaut)
  • .modalSheet — Panneau inférieur avec poignée de glissement (iOS 15+)
  • .dialog — Boîte de dialogue centrée avec arrière-plan assombri

Gestionnaire d'événements

Écoutez les événements du cycle de vie du SDK avec CMPEventHandler. C'est la méthode recommandée pour savoir quand le SDK a terminé son initialisation, quand l'interface est affichée et quand elle est fermée.

Événements disponibles (CMPEventType) :

  • .sdkInit — Initialisation du SDK lancée
  • .ready — Initialisation du SDK terminée (GEO, configuration et fournisseurs chargés)
  • .uiDisplay — L'interface de consentement est affichée
  • .uiClose — L'interface de consentement est fermée

Abonnez-vous aux événements avant d'appeler initialize() pour recevoir tous les événements :

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

Vous pouvez également vous abonner depuis un contrôleur de vue :

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

Pour se désabonner :

UniConsentCMP.shared.unsubscribe(self)

CMPUIDelegate (ancien)

Vous pouvez également écouter la fermeture du consentement avec 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())
    }
}

Vérification automatique de l'expiration du consentement lors de la mise à jour de la vendorList :

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

Récupérer la tcString si nécessaire :

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

Lire le statut du consentement :

// 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()

Réinitialiser le statut du consentement si nécessaire :

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

Synchroniser le consentement vers WebView

Si votre application ouvre une WKWebView qui charge une page web avec le tag CMP UniConsent, vous pouvez transmettre le statut de consentement natif afin que le tag CMP reconnaisse le consentement existant et n'affiche pas la bannière à nouveau.

Appelez syncConsent(to:) avant de charger la page 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];

Configurer les valeurs par défaut du statut de consentement (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/>

Contrôler les analyses en fonction des indicateurs de consentement :

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

Plus d'informations sur Configurer le mode de consentement pour les applications

Remarques

  1. Les utilisateurs doivent avoir la possibilité d'accéder à un bouton ou un lien « Paramètres de confidentialité » dans la section des paramètres de votre application afin d'ouvrir l'interface CMP.
  2. Vous pouvez utiliser la fonction shouldRequestConsent() pour vérifier si vous devez demander un nouveau consentement en fonction du statut. Affichez l'interface CMP selon les besoins lorsqu'un utilisateur ouvre l'application.
  3. À partir de la version 25.6.1 du SDK, vous n'avez plus besoin d'envoyer manuellement les options de consentement pour FirebaseAnalytics ou certains SDK AAP pris en charge — ils sont gérés automatiquement par le SDK. Pour plus d'informations, consultez Qu'est-ce que Google AAP et Google MMP pour les applications mobiles ?.