Per iniziare

Ai sensi del Consenso degli utenti dell'UE di Google Norme, devi mostrare determinate informative agli utenti nello Spazio economico europeo (SEE) con il Regno Unito e ottenere il loro consenso all'utilizzo dei cookie o di altri tipi di archiviazione locale; laddove richiesto dalla legge e di utilizzare dati personali (ad esempio l'ID pubblicità) per pubblicare annunci. Queste norme riflettono i requisiti della direttiva e-Privacy e delle Regolamento generale sulla protezione dei dati (GDPR).

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. Tutte queste configurazioni ora possono essere gestiti in Ad Manager Privacy e i messaggi.

Prerequisiti

Crea un tipo di messaggio

Crea messaggi per gli utenti con uno tipi di messaggi per gli utenti disponibili nel menu a discesa Privacy e nella scheda Messaggistica di Ad Manager . L'SDK UMP tenta di visualizzare messaggio utente creato dall' Ad Manager ID applicazione nel progetto. Se non viene configurato alcun messaggio per la tua applicazione, l'SDK restituisce un errore.

Per ulteriori dettagli, vedi 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 la finestra di dialogo del progetto Podfile e aggiungi questa riga al target dell'app:

pod 'GoogleUserMessagingPlatform'

Quindi, esegui questo comando:

pod install --repo-update

Se non hai mai utilizzato CocoaPods, consulta l'articolo sull'utilizzo CocoaPods per i dettagli su come e come creare e utilizzare Podfile.

Gestore pacchetti Swift

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

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

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

    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 nuovi progetti, consigliamo di utilizzare la versione principale fino alla successiva.

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

Download manuale

L'altro metodo per importare l'SDK è farlo manualmente.

Scarica l'SDK

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

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

Swift

import UserMessagingPlatform

Objective-C

#include <UserMessagingPlatform/UserMessagingPlatform.h>

Aggiungi l'ID applicazione

Puoi trovare il tuo ID applicazione nel UI di Ad Manager. Aggiungi l'ID al tuo Info.plist con il seguente snippet di codice:

<key>GADApplicationIdentifier</key>
<string>ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy</string>

Devi richiedere un aggiornamento delle informazioni sul consenso dell'utente in ogni app avvia utilizzando requestConsentInfoUpdateWithParameters:completionHandler:. Ciò determina se l'utente deve fornire il consenso, se non l'ha già fatto, oppure se il consenso è 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 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. completion handler viene richiamato dopo la chiusura del modulo. 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 effettuato una scelta o lo ha ignorato del modulo, inserisci questa logica nel completion handler per il modulo.

Richiedi annunci

Prima di richiedere annunci nella tua app, verifica di aver ottenuto il consenso dall'utente utilizzando UMPConsentInformation.sharedInstance.canRequestAds. Esistono due metodi luoghi 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 latenza best practice, ti consigliamo di non attendere il completamento della richiamata per 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 tentare di richiedere annunci. L'SDK UMP utilizza lo stato del consenso della precedente durante la sessione.

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 di privacy

Alcuni moduli di consenso richiedono all'utente di modificare il proprio consenso in qualsiasi momento. Adegua i seguenti passaggi per implementare un pulsante delle opzioni per la privacy, se necessario.

A questo scopo:

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

L'esempio seguente mostra come presentare il modulo per le opzioni sulla privacy da 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 questi passaggi per registrare il dispositivo di test in modo programmatico. Assicurati di rimuovere 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 passiamo un elenco degli 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 fosse che si trovano 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 il lo stato desiderato dell'SDK per simulare l'esperienza di 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