Inizia

L'SDK Google User Messaging Platform (UMP) è uno strumento per la privacy e la messaggistica per per aiutarti a gestire le scelte relative alla privacy. Per ulteriori informazioni, vedi Informazioni su privacy e di messaggistica.

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 AdMob . L'SDK UMP tenta di visualizzare messaggio sulla privacy creato dall' AdMob ID applicazione nel progetto.

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 AdMob. 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:. Questa richiesta controlla le seguenti:

  • Se il consenso è obbligatorio. Ad esempio, il consenso è richiesto per la prima volta oppure la decisione di consenso precedente è scaduta.
  • Indica se è necessario un punto di ingresso per le opzioni di privacy. Alcuni messaggi sulla privacy richiedono alle app di consentire agli utenti di modificare le proprie opzioni di privacy in qualsiasi momento.

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 privacy message 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 privacy message form.
          }];
}

Carica e presenta un modulo di messaggio sulla privacy, se necessario

Dopo aver ricevuto lo stato del consenso più aggiornato, chiama loadAndPresentIfRequiredFromViewController:completionHandler: per caricare i moduli richiesti raccogliere il consenso degli utenti. Dopo il caricamento, i moduli vengono visualizzati 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.

Opzioni di privacy

Alcuni moduli di messaggi sulla privacy vengono presentati da un modello di , consentendo agli utenti di gestire le proprie opzioni di privacy in qualsiasi momento. Per scoprire di più sul messaggio che gli utenti vedono nelle opzioni della privacy del punto di accesso, consulta Tipi di messaggi per gli utenti disponibili:

Per implementare un punto di ingresso delle opzioni di privacy, completa i seguenti passaggi:

  1. Controlla UMPConsentInformation.sharedInstance.privacyOptionsRequirementStatus.
  2. Se un punto di ingresso delle opzioni di privacy aggiungi un elemento UI visibile e interattivo alla tua app.
  3. Attiva il modulo per le opzioni sulla privacy utilizzando presentPrivacyOptionsFormFromViewController:completionHandler:.

Il seguente esempio di codice illustra questi passaggi:

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

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:

  • Dopo aver raccolto il consenso nella sessione corrente.
  • 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...];
  });
}

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