Per iniziare

Secondo le Norme relative al consenso degli utenti dell'UE di Google, è obbligatorio informare gli utenti nello Spazio economico europeo (SEE) e nel Regno Unito e ricevere il loro consenso per l'utilizzo dei cookie o di altri tipi di archiviazione locale, ove richiesto dalla legge, nonché di utilizzare dati personali (ad esempio l'ID pubblicità) per la pubblicazione di annunci. Queste norme riflettono i requisiti della direttiva e-Privacy e del Regolamento generale sulla protezione dei dati (GDPR) dell'UE.

Per supportare i publisher nell'adempimento degli obblighi previsti da queste norme, Google offre l'SDK User Messaging Platform (UMP). L'SDK UMP è stato aggiornato per supportare i più recenti standard IAB. Ora tutte queste configurazioni possono essere gestite comodamente nella sezione Interactive Media Ads Privacy e messaggi.

Puoi vedere un'implementazione IMA funzionante con l'SDK UMP nelle app di esempio Objective-C o Swift UMP.

Prerequisiti

Crea un tipo di messaggio

Crea messaggi per gli utenti con uno dei tipi di messaggi per gli utenti disponibili nella scheda Privacy e messaggi del tuo account Ad Manager . L'SDK UMP tenta di visualizzare un messaggio utente creato dall' Interactive Media Ads ID applicazione impostato nel progetto. Se non viene configurato alcun messaggio per la tua applicazione, l'SDK restituisce un errore.

Per maggiori dettagli, consulta Informazioni su privacy e messaggi.

Importa l'SDK

L'SDK UMP non è incluso come dipendenza dell'SDK IMA, quindi devi aggiungerlo esplicitamente personalmente.

CocoaPods (opzione preferita)

Il modo più semplice per importare l'SDK in un progetto iOS è utilizzare CocoaPods. Apri il podfile del progetto e aggiungi questa riga alla destinazione dell'app:

pod 'GoogleUserMessagingPlatform'

Quindi, esegui questo comando:

pod install --repo-update

Se non hai mai utilizzato CocoaPods, consulta Utilizzo di CocoaPods per informazioni dettagliate su come creare e utilizzare i file di pod.

Gestore pacchetti Swift

L'SDK UMP supporta anche il gestore pacchetti Swift. Segui questi passaggi per importare il pacchetto Swift.

  1. In Xcode, installa il pacchetto Swift SDK UMP andando su File > Add Packages... (File > Aggiungi pacchetti...).

  2. Nel prompt visualizzato, cerca il repository GitHub del pacchetto UMP SDK Swift Package:

    https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git
    
  3. Seleziona la versione del pacchetto Swift SDK UMP che vuoi utilizzare. Per i nuovi progetti, consigliamo di utilizzare Up to Next Major Version.

Xcode risolve le dipendenze dei pacchetti e le scarica in background. Per maggiori dettagli su come aggiungere dipendenze dei pacchetti, consulta l'articolo di Apple.

Devi richiedere un aggiornamento delle informazioni sul consenso dell'utente a ogni avvio dell'app utilizzando requestConsentInfoUpdateWithParameters:completionHandler:. In questo modo viene stabilito se l'utente deve fornire il consenso, se non l'ha già fatto o se è scaduto.

Ecco un esempio di come controllare lo stato da un UIViewController nel metodo viewDidLoad().

Swift

override func viewDidLoad() {
  super.viewDidLoad()

  // Request an update for the consent information.
  UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: nil) {
    [weak self] requestConsentError in
    guard let self else { return }

    if let consentError = requestConsentError {
      // Consent gathering failed.
      return print("Error: \(consentError.localizedDescription)")
    }

    // TODO: Load and present the consent form.
  }
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];

  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:nil
          completionHandler:^(NSError *_Nullable requestConsentError) {
            if (requestConsentError) {
              // Consent gathering failed.
              NSLog(@"Error: %@", requestConsentError.localizedDescription);
              return;
            }

            // TODO: Load and present the consent form.
          }];
}

Carica e presenta un modulo di consenso, se necessario

Dopo aver ricevuto lo stato del consenso più aggiornato, chiama loadAndPresentIfRequiredFromViewController:completionHandler: il corso UMPConsentForm per caricare un modulo di consenso. Se lo stato del consenso è obbligatorio, l'SDK carica un modulo e lo presenta immediatamente dal view controllerfornito. Il campo completion handler viene richiamato dopo che il modulo è stato ignorato. Se il consenso non è richiesto, il completion handler viene richiamato immediatamente.

Swift

override func viewDidLoad() {
  super.viewDidLoad()

  // Request an update for the consent information.
  UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: nil) {
    [weak self] requestConsentError in
    guard let self else { return }

    if let consentError = requestConsentError {
      // Consent gathering failed.
      return print("Error: \(consentError.localizedDescription)")
    }

    UMPConsentForm.loadAndPresentIfRequired(from: self) {
      [weak self] loadAndPresentError in
      guard let self else { return }

      if let consentError = loadAndPresentError {
        // Consent gathering failed.
        return print("Error: \(consentError.localizedDescription)")
      }

      // Consent has been gathered.
    }
  }
}

Objective-C

- (void)viewDidLoad {
  [super viewDidLoad];

  __weak __typeof__(self) weakSelf = self;
  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:nil
          completionHandler:^(NSError *_Nullable requestConsentError) {
            if (requestConsentError) {
              // Consent gathering failed.
              NSLog(@"Error: %@", requestConsentError.localizedDescription);
              return;
            }

            __strong __typeof__(self) strongSelf = weakSelf;
            if (!strongSelf) {
              return;
            }

            [UMPConsentForm loadAndPresentIfRequiredFromViewController:strongSelf
                completionHandler:^(NSError *loadAndPresentError) {
                  if (loadAndPresentError) {
                    // Consent gathering failed.
                    NSLog(@"Error: %@", loadAndPresentError.localizedDescription);
                    return;
                  }

                  // Consent has been gathered.
                }];
          }];
}

Se devi eseguire un'azione dopo che l'utente ha scelto o ignorato il modulo, inserisci tale logica nel completion handler modulo.

Richiedi annunci

Prima di richiedere annunci nella tua app, verifica di aver ottenuto il consenso da parte dell'utente che utilizza UMPConsentInformation.sharedInstance.canRequestAds. Ci sono due punti da controllare durante la raccolta del consenso:

  1. Una volta raccolto il consenso nella sessione corrente,
  2. Subito dopo aver chiamato requestConsentInfoUpdateWithParameters:completionHandler:. È possibile che il consenso sia stato ottenuto nella sessione precedente. Come best practice sulla latenza, ti consigliamo di non attendere il completamento del callback per poter iniziare a caricare gli annunci il prima possibile dopo il lancio dell'app.

Se si verifica un errore durante la procedura di raccolta del consenso, dovresti comunque tentare di richiedere gli annunci. L'SDK UMP utilizza lo stato del consenso della sessione precedente.

Swift

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    // Request an update for the consent information.
    UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: nil) {
      [weak self] requestConsentError in
      guard let self else { return }

      if let consentError = requestConsentError {
        // Consent gathering failed.
        return print("Error: \(consentError.localizedDescription)")
      }

      UMPConsentForm.loadAndPresentIfRequired(from: self) {
        [weak self] loadAndPresentError in
        guard let self else { return }

        if let consentError = loadAndPresentError {
          // Consent gathering failed.
          return print("Error: \(consentError.localizedDescription)")
        }

        // Consent has been gathered.
        if UMPConsentInformation.sharedInstance.canRequestAds {
          self.startImaSdk()
        }
      }
    }
    
    // Check if you can initialize the IMA SDK in parallel
    // while checking for new consent information. Consent obtained in
    // the previous session can be used to request ads.
    if UMPConsentInformation.sharedInstance.canRequestAds {
      startImaSdk()
    }
  }
  
  private func startImaSdk() {
    // Create an IMAAdsLoader instance.
    adsLoader = IMAAdsLoader(settings: nil)

    // TODO: Create an IMAAdDisplayContainer and IMAAdsRequest, then make
    // a request for ads.
  }
}

Objective-C

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  __weak __typeof__(self) weakSelf = self;
  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:nil
          completionHandler:^(NSError *_Nullable requestConsentError) {
            if (requestConsentError) {
              // Consent gathering failed.
              NSLog(@"Error: %@", requestConsentError.localizedDescription);
              return;
            }
            __strong __typeof__(self) strongSelf = weakSelf;
            if (!strongSelf) {
              return;
            }

            [UMPConsentForm loadAndPresentIfRequiredFromViewController:strongSelf
                completionHandler:^(NSError *loadAndPresentError) {
                  if (loadAndPresentError) {
                    // Consent gathering failed.
                    NSLog(@"Error: %@", loadAndPresentError.localizedDescription);
                    return;
                  }

                  // Consent has been gathered.
                  __strong __typeof__(self) strongSelf = weakSelf;
                  if (!strongSelf) {
                    return;
                  }

                  if (UMPConsentInformation.sharedInstance.canRequestAds) {
                    [strongSelf startImaSdk];
                  }
                }];
          }];

  // Check if you can initialize the Google IMA SDK in parallel
  // while checking for new consent information. Consent obtained in
  // the previous session can be used to request ads.
  if (UMPConsentInformation.sharedInstance.canRequestAds) {
    [self startImaSdk];
  }
}

- (void)startImaSdk {
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    // Create an IMAAdsLoader instance.
    self.adsLoader = [[IMAAdsLoader alloc] init];

    // TODO: Create an IMAAdDisplayContainer and IMAAdsRequest, then make
    // a request for ads.
  });
}

Opzioni di privacy

Alcuni moduli di consenso richiedono all'utente di modificare il proprio consenso in qualsiasi momento. Segui i passaggi riportati di seguito per implementare un pulsante delle opzioni sulla privacy, se necessario.

A questo scopo:

  1. Implementare un elemento UI, ad esempio un pulsante nella pagina delle impostazioni dell'app, che può attivare un modulo per le opzioni sulla privacy.
  2. Una volta loadAndPresentIfRequiredFromViewController:completionHandler: completato, controlla privacyOptionsRequirementStatus per stabilire se visualizzare l'elemento UI che può presentare il modulo delle opzioni di privacy.
  3. Quando un utente interagisce con l'elemento UI, chiama presentPrivacyOptionsFormFromViewController:completionHandler: per mostrare il modulo in modo che l'utente possa aggiornare le proprie opzioni di privacy in qualsiasi momento.

L'esempio seguente mostra come presentare il modulo per le opzioni sulla privacy da un UIBarButtonItem.

Swift

@IBOutlet weak var privacySettingsButton: UIBarButtonItem!

var isPrivacyOptionsRequired: Bool {
  return UMPConsentInformation.sharedInstance.privacyOptionsRequirementStatus == .required
}

override func viewDidLoad() {
  // ...

  // Request an update for the consent information.
  UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: parameters) {
    // ...

    UMPConsentForm.loadAndPresentIfRequired(from: self) {
      //...

      // Consent has been gathered.

      // Show the button if privacy options are required.
      self.privacySettingsButton.isEnabled = isPrivacyOptionsRequired
    }
  }
  // ...
}

// Present the privacy options form when a user interacts with the
// privacy settings button.
@IBAction func privacySettingsTapped(_ sender: UIBarButtonItem) {
  UMPConsentForm.presentPrivacyOptionsForm(from: self) {
    [weak self] formError in
    guard let self, let formError else { return }

    // Handle the error.
  }
}

Objective-C

@interface ViewController ()
@property(weak, nonatomic) IBOutlet UIBarButtonItem *privacySettingsButton;
@end

- (BOOL)isPrivacyOptionsRequired {
  return UMPConsentInformation.sharedInstance.privacyOptionsRequirementStatus ==
         UMPPrivacyOptionsRequirementStatusRequired;
}

- (void)viewDidLoad {
  // ...

  __weak __typeof__(self) weakSelf = self;
  // Request an update for the consent information.
  [UMPConsentInformation.sharedInstance
      requestConsentInfoUpdateWithParameters:parameters
          completionHandler:^(NSError *_Nullable requestConsentError) {
            // ...

            [UMPConsentForm loadAndPresentIfRequiredFromViewController:strongSelf
                completionHandler:^(NSError *loadAndPresentError) {
                  // ...

                  // Consent has been gathered.

                  // Show the button if privacy options are required.
                  strongSelf.privacySettingsButton.enabled = isPrivacyOptionsRequired;
                }];
          }];
}

// Present the privacy options form when a user interacts with your
// privacy settings button.
- (IBAction)privacySettingsTapped:(UIBarButtonItem *)sender {
  [UMPConsentForm presentPrivacyOptionsFormFromViewController:self
                                completionHandler:^(NSError *_Nullable formError) {
                                  if (formError) {
                                    // Handle the error.
                                  }
                                }];
}

Test in corso

Se vuoi testare l'integrazione nella tua app durante lo sviluppo, segui questi passaggi per registrare il dispositivo di test in modo programmatico. Assicurati di rimuovere il codice che imposta questi ID dispositivo di test prima di rilasciare l'app.

  1. Chiama il numero requestConsentInfoUpdateWithParameters:completionHandler:.
  2. Controlla nell'output del log un messaggio simile all'esempio seguente, che mostra l'ID dispositivo e come aggiungerlo come dispositivo di test:

    <UMP SDK>To enable debug mode for this device, set: UMPDebugSettings.testDeviceIdentifiers = @[2077ef9a63d2b398840261c8221a0c9b]
    
  3. Copia l'ID del dispositivo di test negli appunti.

  4. Modifica il codice per chiamare UMPDebugSettings().testDeviceIdentifiers e passare un elenco dei tuoi ID dispositivo di test.

    Swift

    let parameters = UMPRequestParameters()
    let debugSettings = UMPDebugSettings()
    debugSettings.testDeviceIdentifiers = ["TEST-DEVICE-HASHED-ID"]
    parameters.debugSettings = debugSettings
    // Include the UMPRequestParameters in your consent request.
    UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(
        with: parameters,
        completionHandler: { error in
          ...
        })
    

    Objective-C

    UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
    UMPDebugSettings *debugSettings = [[UMPDebugSettings alloc] init];
    debugSettings.testDeviceIdentifiers = @[ @"TEST-DEVICE-HASHED-ID" ];
    parameters.debugSettings = debugSettings;
    // Include the UMPRequestParameters in your consent request.
    [UMPConsentInformation.sharedInstance
        requestConsentInfoUpdateWithParameters:parameters
                            completionHandler:^(NSError *_Nullable error){
                              ...
    }];
    

Forzare un'area geografica

L'SDK UMP consente di testare il comportamento della tua app come se il dispositivo si trovasse nello Spazio economico europeo o nel Regno Unito utilizzando the debugGeography property of type UMPDebugGeography on UMPDebugSettings. Tieni presente che le impostazioni di debug funzionano solo sui dispositivi di test.

Swift

let parameters = UMPRequestParameters()
let debugSettings = UMPDebugSettings()
debugSettings.testDeviceIdentifiers = ["TEST-DEVICE-HASHED-ID"]
debugSettings.geography = .EEA
parameters.debugSettings = debugSettings
// Include the UMPRequestParameters in your consent request.
UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(
    with: parameters,
    completionHandler: { error in
      ...
    })

Objective-C

UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
UMPDebugSettings *debugSettings = [[UMPDebugSettings alloc] init];
debugSettings.testDeviceIdentifiers = @[ @"TEST-DEVICE-HASHED-ID" ];
debugSettings.geography = UMPDebugGeographyEEA;
parameters.debugSettings = debugSettings;
// Include the UMPRequestParameters in your consent request.
[UMPConsentInformation.sharedInstance
    requestConsentInfoUpdateWithParameters:parameters
                         completionHandler:^(NSError *_Nullable error){
                           ...
}];

Durante il test della tua app con l'SDK UMP, potrebbe essere utile reimpostare lo stato dell'SDK in modo da simulare l'esperienza della prima installazione di un utente. L'SDK fornisce il reset metodo per farlo.

Swift

UMPConsentInformation.sharedInstance.reset()

Objective-C

[UMPConsentInformation.sharedInstance reset];