Según la Política de Consentimiento de Usuarios de la UE de Google, debes divulgar cierta 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 de la UE y el Reglamento General de Protección de Datos (GDPR).
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 ser compatible con los estándares más recientes de la IAB. Todas estas configuraciones ahora se pueden controlar de forma conveniente en AdMob la privacidad y la mensajería.
Requisitos previos
- Completa la guía de introducción.
- Si estás trabajando en los requisitos relacionados con el GDPR, consulta Cómo los requisitos de IAB afectan los mensajes de consentimiento para usuarios de la UE
Cómo crear 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 deAdMob . 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 (preferido)
El SDK de UMP se incluye como una dependencia del Pod del SDK de anuncios de Google para dispositivos móviles a partir de la versión 7.64.0.
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 'Google-Mobile-Ads-SDK'
Luego, ejecuta el comando siguiente:
pod install --repo-update
Si eres nuevo en CocoaPods, consulta Cómo usar CocoaPods para obtener detalles sobre cómo crear y usar Podfiles.
Descarga manual
La otra forma de importar el SDK es hacerlo de forma manual.
Luego, 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 con el siguiente comando:
Swift
import UserMessagingPlatform
Objective‑C
#include <UserMessagingPlatform/UserMessagingPlatform.h>
Solicitud de información de consentimiento
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 el usuario debe dar su consentimiento si aún no lo hizo o si venció.
Este es un ejemplo de cómo verificar el estado de un UIViewController
en el método viewDidLoad()
.
Swift
override func viewDidLoad() {
super.viewDidLoad()
// Create a UMPRequestParameters object.
let parameters = UMPRequestParameters()
// Set tag for under age of consent. false means users are not under age
// of consent.
parameters.tagForUnderAgeOfConsent = false
// Request an update for the consent information.
UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: parameters) {
[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];
// Create a UMPRequestParameters object.
UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
// Set tag for under age of consent. NO means users are not under age
// of consent.
parameters.tagForUnderAgeOfConsent = NO;
// Request an update for the consent information.
[UMPConsentInformation.sharedInstance
requestConsentInfoUpdateWithParameters:parameters
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 hayas recibido 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 desde el view controllerproporcionado. Se llama a completion handlerdespués de descartar el formulario. Si no se requiere consentimiento, se llama a completion handlerde inmediato.
Swift
override func viewDidLoad() {
super.viewDidLoad()
// Create a UMPRequestParameters object.
let parameters = UMPRequestParameters()
// Set tag for under age of consent. false means users are not under age
// of consent.
parameters.tagForUnderAgeOfConsent = false
// Request an update for the consent information.
UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: parameters) {
[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];
// Create a UMPRequestParameters object.
UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
// Set tag for under age of consent. NO means users are not under age
// of consent.
parameters.tagForUnderAgeOfConsent = NO;
__weak __typeof__(self) weakSelf = self;
// Request an update for the consent information.
[UMPConsentInformation.sharedInstance
requestConsentInfoUpdateWithParameters:parameters
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 elegido 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 que debes verificar cuando obtienes el consentimiento:
- Una vez que se haya obtenido 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 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 tu app.
Si se produce un error durante el proceso de obtención de 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()
// Create a UMPRequestParameters object.
let parameters = UMPRequestParameters()
// Set tag for under age of consent. false means users are not under age
// of consent.
parameters.tagForUnderAgeOfConsent = false
// Request an update for the consent information.
UMPConsentInformation.sharedInstance.requestConsentInfoUpdate(with: parameters) {
[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];
// Create a UMPRequestParameters object.
UMPRequestParameters *parameters = [[UMPRequestParameters alloc] init];
// Set tag for under age of consent. NO means users are not under age
// of consent.
parameters.tagForUnderAgeOfConsent = NO;
__weak __typeof__(self) weakSelf = self;
// Request an update for the consent information.
[UMPConsentInformation.sharedInstance
requestConsentInfoUpdateWithParameters:parameters
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 startGoogleMobileAdsSDKOnce];
}
}];
}];
// 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 startGoogleMobileAdsSDKOnce];
}
}
- (void)startGoogleMobileAdsSDKOnce {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Initialize the Google Mobile Ads SDK.
[GADMobileAds.sharedInstance startWithCompletionHandler:nil];
// TODO: Request an ad.
// [GADInterstitialAd loadWithAdUnitID...];
});
}
Pruebas
Si quieres probar la integración en tu app mientras desarrollas, sigue los pasos que se indican a continuación para registrar el dispositivo de prueba de manera programática.
- Llama a
requestConsentInfoUpdateWithParameters:completionHandler:
. Revisa el resultado del registro para ver un mensaje similar al siguiente, que muestra tu ID de dispositivo y cómo agregarlo como un dispositivo de prueba:
<UMP SDK>To enable debug mode for this device, set: UMPDebugSettings.testDeviceIdentifiers = @[2077ef9a63d2b398840261c8221a0c9b]
Copia el ID de tu dispositivo de prueba en el portapapeles.
Modifica tu código para llamar a
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 geografía
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 mediante 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){
...
}];
Restablecer el estado de consentimiento
Cuando pruebes tu app con el SDK de UMP, tal vez te resulte útil restablecer el estado del SDK para simular la primera experiencia de instalación de un usuario.
El SDK proporciona el método reset
para hacerlo.
Swift
UMPConsentInformation.sharedInstance.reset()
Objective‑C
[UMPConsentInformation.sharedInstance reset];