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, laddove richiesto dalla legge, e per l'utilizzo dei 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 UMP (User Messaging Platform). L'SDK UMP è stato aggiornato per supportare i più recenti standard IAB. Tutte queste configurazioni ora possono essere comodamente gestite in AdMob privacy e messaggi.

Prerequisiti

Crea un tipo di messaggio

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

Per maggiori dettagli, consulta Informazioni su privacy e messaggi.

Importa l'SDK

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 è la prima volta che utilizzi CocoaPods, consulta la pagina relativa all'utilizzo di CocoaPods per informazioni dettagliate su come creare e utilizzare i podfile.

Gestore pacchetti Swift

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

  1. In Xcode, installa il pacchetto Swift dell'SDK UMP andando su File > Aggiungi pacchetti....

  2. Nel prompt visualizzato, cerca il repository GitHub dell'SDK Swift di UMP:

    https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git
    
  3. Seleziona la versione del pacchetto Swift dell'SDK UMP che vuoi utilizzare. Per i nuovi progetti, consigliamo di utilizzare la versione principale successiva.

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

Download manuale

L'altro modo di importare l'SDK è manualmente.

Scarica l'SDK

Quindi, trascina il framework nel progetto Xcode, assicurandoti di selezionare Copia elementi, se necessario.

Puoi quindi includere il framework in qualsiasi file che ti serve utilizzando:

Swift

import UserMessagingPlatform

Objective-C

#include <UserMessagingPlatform/UserMessagingPlatform.h>

Devi richiedere un aggiornamento delle informazioni sul consenso dell'utente a ogni lancio dell'app, utilizzando requestConsentInfoUpdateWithParameters:completionHandler:. Questo determina se l'utente deve dare il consenso nel caso in cui non l'abbia già fatto o se il consenso è scaduto.

Ecco un esempio di come controllare lo stato di un elemento 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

Importante: le API seguenti sono compatibili con l'SDK UMP versione 2.1.0 o successive.

Dopo aver ricevuto lo stato del consenso più aggiornato, chiama loadAndPresentIfRequiredFromViewController:completionHandler: il UMPConsentForm corso per caricare un modulo di consenso. Se lo stato del consenso è obbligatorio, l'SDK carica un modulo e lo presenta immediatamente dal view controllerspecificato. Il completion handler viene richiamato dopo che il modulo viene ignorato. Se il consenso non è richiesto, il completion handler viene chiamato 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 azioni dopo che l'utente ha scelto o ignorato il modulo, inserisci la logica corrispondente nel completion handlermodulo.

Richiedi annunci

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

  1. Una volta ottenuto 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 in materia di latenza, ti consigliamo di non attendere il completamento del callback in modo da poter iniziare a caricare gli annunci il prima possibile dopo l'avvio dell'app.

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

Swift

class ViewController: UIViewController {

  // Use a boolean to initialize the Google Mobile Ads SDK and load ads once.
  private var isMobileAdsStartCalled = false

  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.startGoogleMobileAdsSDK()
        }
      }
    }
    
    // Check if you can initialize the Google Mobile Ads 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 {
      startGoogleMobileAdsSDK()
    }
  }
  
  private func startGoogleMobileAdsSDK() {
    DispatchQueue.main.async {
      guard !self.isMobileAdsStartCalled else { return }

      self.isMobileAdsStartCalled = true

      // Initialize the Google Mobile Ads SDK.
      GADMobileAds.sharedInstance().start()

      // TODO: Request an ad.
      // GADInterstitialAd.load(...)
    }
  }
}

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 startGoogleMobileAdsSDK];
                  }
                }];
          }];

  // Check if you can initialize the Google Mobile Ads 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 startGoogleMobileAdsSDK];
  }
}

- (void)startGoogleMobileAdsSDK {
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    // Initialize the Google Mobile Ads SDK.
    [GADMobileAds.sharedInstance startWithCompletionHandler:nil];

    // TODO: Request an ad.
    // [GADInterstitialAd loadWithAdUnitID...];
  });
}

Opzioni relative alla privacy

Alcuni moduli di consenso richiedono all'utente di modificare il consenso in qualsiasi momento. Rispetta i seguenti passaggi per implementare un pulsante Opzioni di privacy, se necessario.

A questo scopo:

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

L'esempio seguente mostra come presentare il modulo delle opzioni di 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

Se vuoi testare l'integrazione nella tua app durante lo sviluppo, segui i passaggi riportati di seguito per registrare in modo programmatico il dispositivo di test.

  1. Chiama il numero requestConsentInfoUpdateWithParameters:completionHandler:.
  2. Controlla se nell'output del log è presente un messaggio simile a quello riportato di seguito, che mostra l'ID del tuo 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 dispositivo di test negli appunti.

  4. Modifica il codice per chiamare UMPDebugSettings().testDeviceIdentifiers e trasmettere 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 ti consente di testare il comportamento della tua app come se il dispositivo si trovasse nel SEE 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 la prima installazione di un utente. L'SDK fornisce il reset metodo per farlo.

Swift

UMPConsentInformation.sharedInstance.reset()

Objective-C

[UMPConsentInformation.sharedInstance reset];

Esempi su GitHub

Esempi di integrazione dell'SDK UMP: Swift | Objective-C