De acordo com a Política de consentimento para usuários da União Europeia do Google, é necessário divulgar algumas informações aos usuários no Espaço Econômico Europeu (EEE) e o Reino Unido e receber o consentimento deles para usar cookies ou outro armazenamento local, conforme os requisitos legais, e usar dados pessoais (como ID de publicidade) para veicular anúncios. Essa política reflete os requisitos da Diretiva de privacidade eletrônica da UE e do Regulamento geral de proteção de dados (GDPR).
Para ajudar os editores a cumprir as obrigações determinadas por essa política, o Google oferece o SDK da plataforma de mensagens aos usuários (UMP, na sigla em inglês). O SDK do UMP foi atualizado para aceitar os padrões mais recentes do IAB. Todas essas configurações agora podem ser processadas de forma conveniente em AdMob Privacidade e mensagens.
Pré-requisitos
- Leia o Guia para iniciantes
- Se você estiver trabalhando em requisitos relacionados ao GDPR, leia Como os requisitos do IAB afetam as mensagens de consentimento para a União Europeia
Criar um tipo de mensagem
Crie mensagens de usuários com um dos tipos disponíveis na guia Privacidade e mensagens da sua AdMob conta. O SDK do UMP tenta exibir uma mensagem do usuário criada a partir do AdMob ID do aplicativo definido no seu projeto. Se nenhuma mensagem for configurada para o aplicativo, o SDK retornará um erro.
Saiba mais em Sobre privacidade e mensagens.
Importar o SDK
CocoaPods (preferencial)
O SDK do UMP é incluído como uma dependência do pod do SDK dos anúncios para dispositivos móveis do Google, a partir da versão 7.64.0.
A maneira mais fácil de importar o SDK para um projeto do iOS é usar o CocoaPods. Abra o Podfile do projeto e adicione esta linha ao destino do app:
pod 'Google-Mobile-Ads-SDK'
Em seguida, execute o comando:
pod install --repo-update
Se você não conhece o CocoaPods, consulte Como usar o CocoaPods para detalhes sobre como criar e usar Podfiles.
Download manual
A outra maneira de importar o SDK é manualmente.
Em seguida, arraste o framework para seu projeto do Xcode e selecione Copy items if needed.
Depois, você pode incluir a estrutura em qualquer arquivo que precisar usando:
Swift
import UserMessagingPlatform
Objective-C
#include <UserMessagingPlatform/UserMessagingPlatform.h>
Solicitação de informações de consentimento
Solicite uma atualização das informações de consentimento do usuário a cada inicialização do app usando requestConsentInfoUpdateWithParameters:completionHandler:
. Isso determina se o usuário precisa dar consentimento caso ainda não tenha feito isso ou tenha expirado.
Veja um exemplo de como verificar o status de um UIViewController
no
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.
}];
}
Carregar e apresentar um formulário de consentimento, se necessário
Depois de receber o status de consentimento mais atualizado, chameloadAndPresentIfRequiredFromViewController:completionHandler:
na classeUMPConsentForm
para carregar um formulário de consentimento. Se o status de consentimento for obrigatório, o SDK carregará um formulário e o apresentará imediatamente a partir do view controllerfornecido. O completion handler
é chamado depois que o formulário é dispensado. Se o consentimento não for necessário, o completion handlerserá chamado imediatamente.
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.
}];
}];
}
Se você precisar realizar qualquer ação depois que o usuário fizer uma escolha ou dispensar o formulário, coloque essa lógica no completion handler do formulário.
Solicitar anúncios
Antes de solicitar anúncios no seu app, verifique se você recebeu o consentimento do usuário que usa UMPConsentInformation.sharedInstance.canRequestAds
. Há dois lugares a serem verificados ao obter o consentimento:
- Depois de receber o consentimento na sessão atual.
- Imediatamente após chamar
requestConsentInfoUpdateWithParameters:completionHandler:
. É possível que o consentimento tenha sido dado na sessão anterior. Como prática recomendada de latência, não espere a conclusão do callback para começar a carregar anúncios o mais rápido possível após o início do aplicativo.
Se ocorrer um erro durante o processo de solicitação de consentimento, você ainda precisará tentar solicitar anúncios. O SDK do UMP usa o status de consentimento da sessão 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...];
});
}
Teste
Se você quiser testar a integração no app durante o desenvolvimento, siga as etapas abaixo para registrar o dispositivo de teste de maneira programática.
- Chame
requestConsentInfoUpdateWithParameters:completionHandler:
. Verifique a saída do registro de uma mensagem parecida com a abaixo, que mostra o ID do dispositivo e como adicioná-lo como um dispositivo de teste:
<UMP SDK>To enable debug mode for this device, set: UMPDebugSettings.testDeviceIdentifiers = @[2077ef9a63d2b398840261c8221a0c9b]
Copie o ID do dispositivo de teste para a área de transferência.
Modifique seu código para chamar
UMPDebugSettings().testDeviceIdentifiers
e transmitir uma lista dos IDs de dispositivos de teste.
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){
...
}];
Forçar uma região geográfica
O SDK do UMP oferece uma maneira de testar o comportamento do seu app como se o dispositivo estivesse
localizado no EEE ou no Reino Unido usando the debugGeography
property of type UMPDebugGeography
on UMPDebugSettings
. As
configurações de depuração só funcionam em dispositivos de teste.
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){
...
}];
Redefinir estado de consentimento
Ao testar seu app com o SDK do UMP, pode ser útil redefinir o
estado do SDK para que você possa simular a primeira experiência de instalação de um usuário.
O SDK fornece o método reset
para fazer isso.
Swift
UMPConsentInformation.sharedInstance.reset()
Objective-C
[UMPConsentInformation.sharedInstance reset];