Cómo comenzar

El SDK de Google User Messaging Platform (UMP) es una herramienta de mensajería y privacidad para para administrar las opciones de privacidad. Para obtener más información, consulta Acerca de Privacidad y mensajería.

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 AdMob de servicio predeterminada. El SDK de UMP intenta mostrar un mensaje de privacidad creado a partir del AdMob ID de la aplicación establecido en tu proyecto.

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 AdMob. 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:. Esta solicitud se verifica lo siguiente:

  • Si se requiere consentimiento. Por ejemplo, el consentimiento es obligatorio primera vez o venció la decisión de consentimiento anterior.
  • Si se requiere un punto de entrada de opciones de privacidad. Algunos mensajes de privacidad requerir que las apps permitan a los usuarios modificar sus opciones de privacidad en cualquier momento

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

Carga y presenta un formulario de mensaje de privacidad si es necesario

Una vez que recibas el estado de consentimiento más actualizado, llama loadAndPresentIfRequiredFromViewController:completionHandler: para cargar los formularios necesarios para obtener el consentimiento del usuario. Después de la carga, los formularios se presentan 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.

Opciones de privacidad

Algunos formularios de mensajes de privacidad se presentan desde un contenedor el punto de entrada de las opciones, lo que permite a los usuarios administrar sus opciones de privacidad en cualquier momento. Para obtener más información sobre qué mensaje ven los usuarios en las opciones de privacidad punto de entrada, consulta Tipos de mensajes para los usuarios disponibles

Para implementar un punto de entrada de opciones de privacidad, completa los siguientes pasos:

  1. Verifica UMPConsentInformation.sharedInstance.privacyOptionsRequirementStatus.
  2. Si un punto de entrada de las opciones de privacidad , agrega un elemento de la IU visible e interactivo a tu app.
  3. Activa el formulario de opciones de privacidad con presentPrivacyOptionsFormFromViewController:completionHandler:

En el siguiente ejemplo de código, se muestran estos pasos:

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

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:

  • Una vez que se haya recopilado el consentimiento en la sesión actual,
  • 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...];
  });
}

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