Cómo comenzar

Según la Política de Consentimiento de Usuarios de la UE de Google, debes divulgar determinada información a los usuarios del Espacio Económico Europeo (EEE) y el Reino Unido, y obtener su consentimiento para usar cookies y otro tipo de almacenamiento local, cuando sea un requisito legal, y usar datos personales (como el ID del anuncio) para publicar anuncios. Esta política refleja los requisitos de la Directiva de Privacidad Electrónica y el Reglamento General de Protección de Datos (GDPR) de la UE.

Para ayudar a los publicadores a cumplir con sus obligaciones en virtud de esta política, Google ofrece el SDK de User Messaging Platform (UMP). El SDK de UMP se actualizó para admitir los estándares más recientes de IAB. Todas estas configuraciones ahora se pueden administrar de forma conveniente en AdMob Privacidad y mensajería.

Requisitos previos

Crea un tipo de mensaje

Crea mensajes para los usuarios con uno de los tipos de mensajes disponibles para los usuarios en la pestaña Privacidad y mensajería de tu cuenta de AdMob . El SDK de UMP intenta mostrar un mensaje del usuario creado a partir del AdMob ID de aplicación configurado en tu proyecto. Si no se configura ningún mensaje para tu aplicación, el SDK muestra un error.

Para obtener más detalles, consulta Acerca de la privacidad y la mensajería.

Importa el SDK

CocoaPods (opción preferida)

La forma más fácil de importar el SDK a un proyecto de iOS es usar CocoaPods. Abre el Podfile de tu proyecto y agrega esta línea al destino de tu app:

pod 'GoogleUserMessagingPlatform'

Luego, ejecuta el comando siguiente:

pod install --repo-update

Si eres nuevo en CocoaPods, consulta Usa CocoaPods para obtener detalles sobre cómo crear y usar Podfiles.

Swift Package Manager

El SDK de UMP también es compatible con Swift Package Manager. Sigue estos pasos para importar el paquete de Swift.

  1. En Xcode, navega a File > Add Packages... para instalar el paquete de Swift del SDK de UMP.

  2. En el mensaje que aparece, busca el repositorio de GitHub del paquete Swift del SDK de UMP:

    https://github.com/googleads/swift-package-manager-google-user-messaging-platform.git
    
  3. Selecciona la versión del paquete de Swift del SDK de UMP que quieres usar. Para proyectos nuevos, recomendamos usar Hasta la siguiente versión principal.

Luego, Xcode resuelve las dependencias de tus paquetes y las descarga en segundo plano. Para obtener más detalles sobre cómo agregar dependencias de paquetes, consulta este artículo de Apple.

Descarga manual

La otra forma de importar el SDK es hacerlo de forma manual.

Descarga el SDK

Luego, arrastra el framework a tu proyecto de Xcode y asegúrate de seleccionar Copiar elementos si es necesario.

Luego, puedes incluir el framework en cualquier archivo que necesites usando lo siguiente:

Swift

import UserMessagingPlatform

Objective‑C

#include <UserMessagingPlatform/UserMessagingPlatform.h>

Debes solicitar una actualización de la información de consentimiento del usuario en cada inicio de la app mediante requestConsentInfoUpdateWithParameters:completionHandler:. Esto determina si el usuario debe dar su consentimiento si todavía no lo hizo o si venció.

A continuación, se muestra un ejemplo de cómo verificar el estado de un UIViewController en el método 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.
          }];
}

Carga y presenta un formulario de consentimiento si es necesario

Una vez que recibas el estado de consentimiento más actualizado, llama aloadAndPresentIfRequiredFromViewController:completionHandler: en la claseUMPConsentForm para cargar un formulario de consentimiento. Si el estado de consentimiento es obligatorio, el SDK carga un formulario y lo presenta de inmediato del view controllerproporcionado. completion handler se llama después de que se descarta el formulario. Si no se requiere el consentimiento, el completion handler se llama de inmediato.

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

Si necesitas realizar alguna acción después de que el usuario haya hecho una elección o descartado el formulario, coloca esa lógica en el completion handlerde tu formulario.

Solicitar anuncios

Antes de solicitar anuncios en tu app, verifica si obtuviste el consentimiento del usuario que usa UMPConsentInformation.sharedInstance.canRequestAds. Hay dos lugares para verificar mientras obtienes el consentimiento:

  1. Una vez que se obtenga el consentimiento en la sesión actual,
  2. Inmediatamente después de llamar a requestConsentInfoUpdateWithParameters:completionHandler: Es posible que se haya obtenido el consentimiento en la sesión anterior. Como práctica recomendada para la latencia, te sugerimos no esperar a que se complete la devolución de llamada para comenzar a cargar anuncios lo antes posible después del lanzamiento de tu app.
.

Si se produce un error durante el proceso de obtención del consentimiento, aún debes intentar solicitar anuncios. El SDK de UMP usa el estado de consentimiento de la sesión anterior.

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

Opciones de privacidad

Algunos formularios de consentimiento requieren que el usuario modifique su consentimiento en cualquier momento. Cumple con los siguientes pasos para implementar un botón de opciones de privacidad si es necesario.

Entonces:

  1. Implementa un elemento de la IU, como un botón en la página de configuración de la app, que pueda activar un formulario de opciones de privacidad.
  2. Una vez que se complete loadAndPresentIfRequiredFromViewController:completionHandler: , marcaprivacyOptionsRequirementStatus para determinar si se muestra el elemento de la IU que puede presentar el formulario de opciones de privacidad.
  3. Cuando un usuario interactúe con tu elemento de la IU, llama apresentPrivacyOptionsFormFromViewController:completionHandler: para mostrar el formulario de modo que el usuario pueda actualizar sus opciones de privacidad en cualquier momento.

En el siguiente ejemplo, se muestra cómo presentar el formulario de opciones de privacidad desde 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.
                                  }
                                }];
}

Prueba

Si quieres probar la integración en tu app mientras desarrollas, sigue estos pasos para registrar tu dispositivo de prueba de manera programática. Asegúrate de quitar el código que establece estos IDs de dispositivos de prueba antes de lanzar la app.

  1. Llama a requestConsentInfoUpdateWithParameters:completionHandler:.
  2. Revisa el resultado del registro en busca de un mensaje similar al siguiente ejemplo, que muestra el ID de tu dispositivo y cómo agregarlo como dispositivo de prueba:

    <UMP SDK>To enable debug mode for this device, set: UMPDebugSettings.testDeviceIdentifiers = @[2077ef9a63d2b398840261c8221a0c9b]
    
  3. Copia el ID del dispositivo de prueba en el portapapeles.

  4. Modifica tu código para llamar UMPDebugSettings().testDeviceIdentifiers y pasar una lista de los IDs de dispositivos de prueba.

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

Fuerza una ubicación geográfica

El SDK de UMP proporciona una forma de probar el comportamiento de tu app como si el dispositivo estuviera ubicado en el EEE o el Reino Unido con the debugGeography property of type UMPDebugGeography on UMPDebugSettings. Ten en cuenta que la configuración de depuración solo funciona en dispositivos de prueba.

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

Cuando pruebas tu app con el SDK de UMP, puede resultarte útil restablecer el estado del SDK para que puedas simular la experiencia de primera instalación de un usuario. Para ello, el SDK proporciona el método reset .

Swift

UMPConsentInformation.sharedInstance.reset()

Objective‑C

[UMPConsentInformation.sharedInstance reset];

Ejemplos en GitHub

Ejemplos de integración del SDK de UMP: Swift | Objective-C