Cómo comenzar

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

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). Se actualizó el SDK de UMP para que sea compatible con los estándares más recientes de la IAB. Ahora, todas estas configuraciones se pueden manejado en Ad Manager privacidad y y la mensajería de los datos.

Requisitos previos

Crea un tipo de mensaje

Crea mensajes de usuario con uno de los tipos de mensajes para los usuarios disponibles en la sección Privacidad y mensajes de tu Ad Manager de servicio predeterminada. El SDK de UMP intenta mostrar un mensaje de usuario creado a partir del Ad Manager ID de aplicación establecido en tu proyecto. Si no se configura ningún mensaje para tu aplicación, el SDK devuelve un error.

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

Importa el SDK

CocoaPods (opción preferida)

La manera más sencilla de importar el SDK a un proyecto de iOS es utilizar CocoaPods. Abre el archivo Podfile 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 Uso de 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, instala el paquete de Swift del SDK de UMP. Para ello, navega a Archivo > Add Packages...

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

    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 nuevos proyectos, te recomendamos usar Up to Next Major Version.

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

Descarga manual

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

Descarga el SDK

Luego, arrastra el framework a tu proyecto Xcode y asegúrate de seleccionar Copiar 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>

Agrega el ID de aplicación

Puedes encontrar el ID de la aplicación en la IU de Ad Manager Agrega el ID a tu Info.plist con el siguiente fragmento de código:

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

Debe solicitar una actualización de la información de consentimiento del usuario en cada aplicación iniciar con requestConsentInfoUpdateWithParameters:completionHandler:. Esto determina si el usuario debe dar su consentimiento si aún no lo hizo si venció el consentimiento.

Este es un ejemplo de cómo verificar el estado de un UIViewController en el 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 loadAndPresentIfRequiredFromViewController:completionHandler: el UMPConsentForm para cargar un formulario de consentimiento. Si el botón el estado de consentimiento es obligatorio, el SDK carga un formulario y lo presenta de inmediato del view controllerproporcionado. El completion handler se llama después de que se descarta el formulario. Si no se requiere el consentimiento, la 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 la descarte el formulario, coloca esa lógica en el archivo completion handler para tu formulario.

Solicitar anuncios

Antes de solicitar anuncios en tu app, verifica si obtuviste el consentimiento del usuario con UMPConsentInformation.sharedInstance.canRequestAds. Existen dos lugares para verificar al obtener 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 una latencia práctica recomendada, te sugerimos que no esperes a que se complete la devolución de llamada para que puedas empezar a cargar anuncios tan pronto como sea posible tras el lanzamiento de tu app.

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

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 requisitos a 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 tu app. que puede activar un formulario de opciones de privacidad.
  2. Una vez que se loadAndPresentIfRequiredFromViewController:completionHandler: complete, revise privacyOptionsRequirementStatus para determinar si se debe mostrar o no 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 presentPrivacyOptionsFormFromViewController:completionHandler: para mostrar el formulario a fin de 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 del 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 código que establece estos IDs de dispositivo de prueba antes de lanzar la app.

  1. Llama a requestConsentInfoUpdateWithParameters:completionHandler:.
  2. Revisa el resultado del registro para ver si hay un mensaje similar al siguiente ejemplo, que muestra tu ID de 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 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){
                              ...
    }];
    

Fuerza una ubicación geográfica

El SDK de UMP proporciona una forma de probar el comportamiento de tu app como si el dispositivo no estuviera ubicados 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 pruebes tu app con el SDK de UMP, puede resultarte útil restablecer del SDK para que puedas simular la experiencia de la 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