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, así como utilizar 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 la IAB. Todas estas configuraciones ahora se pueden manejar de forma conveniente en Ad Manager privacidad y mensajería.

Requisitos previos

Crea un tipo de mensaje

Crea mensajes para los usuarios con uno de los tipos de mensajes para el usuario disponibles en la pestaña Privacidad y mensajería de tu cuenta de Ad Manager . El SDK de UMP intenta mostrar un mensaje para el usuario creado a partir del Ad Manager 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 archivo 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 es la primera vez que usas CocoaPods, consulta cómo usar 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 del SDK de UMP Swift.

  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, te recomendamos usar Hasta la siguiente versión principal.

Xcode resuelve las dependencias de tus paquetes y las descarga en segundo plano. Para conocer 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

A continuación, arrastra el framework a tu proyecto de Xcode y asegúrate de seleccionar Copy items if needed.

Luego, puedes incluir el framework en cualquier archivo que necesites utilizando 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 lanzamiento de la app mediante requestConsentInfoUpdateWithParameters:completionHandler:. Esto determina si tu usuario debe dar su consentimiento si aún no lo ha hecho 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

Importante: Las siguientes APIs son compatibles con el SDK de UMP 2.1.0 o una versión posterior.

Una vez que hayas recibido el estado de consentimiento más actualizado, llama aloadAndPresentIfRequiredFromViewController:completionHandler: en la claseUMPConsentForm para cargar un formulario de consentimiento. Si se requiere el estado de consentimiento, el SDK carga un formulario y lo presenta de inmediato desde el view controllerproporcionado. Se llama a la completion handler después de que se cierra el formulario. Si no se requiere 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 haya 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 que debes verificar cuando 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 de latencia, te sugerimos no esperar a que se complete la devolución de llamada para que puedas comenzar a cargar anuncios lo antes posible después del lanzamiento de la 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. Sigue los pasos que se indican a continuación 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: , verificaprivacyOptionsRequirementStatus para determinar si quieres mostrar 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 de 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 la 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. Busca el resultado del registro en busca de un mensaje similar al siguiente ejemplo, que muestre el ID de tu dispositivo y cómo agregarlo como un dispositivo de prueba:

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

  4. Modifica tu código para llamar UMPDebugSettings().testDeviceIdentifiers y pasar una lista de los IDs de tus 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){
                              ...
    }];
    

Cómo forzar una ubicación geográfica

El SDK de UMP proporciona una forma de probar el comportamiento de tu app como si el dispositivo se encontrara en el EEE o el Reino Unido con the debugGeography property of type UMPDebugGeography on UMPDebugSettings. Ten en cuenta que esta configuració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 pruebes tu app con el SDK de UMP, tal vez te resulte útil restablecer el estado del SDK para simular la experiencia de la primera instalación de un usuario. El SDK proporciona el método reset para hacerlo.

Swift

UMPConsentInformation.sharedInstance.reset()

Objective‑C

[UMPConsentInformation.sharedInstance reset];

Ejemplos en GitHub

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