Neste guia, mostramos como solicitar informações de consentimento do usuário por um formulário e verificar o consentimento do usuário ao solicitar anúncios com o SDK da plataforma de mensagens de usuários (UMP, na sigla em inglês) em um app SwiftUI.
Pré-requisitos
- Leia o Guia explicativo.
Solicitação de informações de consentimento
Solicite uma atualização das informações de consentimento do usuário a cada inicialização
de app usando requestConsentInfoUpdateWithParameters:completionHandler:
. Isso determina se o usuário precisa dar consentimento (caso ainda não tenha feito isso) ou se ele expirou.
Confira um exemplo de como verificar o status de um
View
no
método
onAppear(perform:)
.
struct ContentView: View {
@State private var hasViewAppeared = false
var body: some View {
VStack {
...
}
.onAppear {
// Gather consent only the first time the view appears.
guard !hasViewAppeared else { return }
hasViewAppeared = true
// 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) {
(requestConsentError) in
if let consentError = requestConsentError {
// Consent gathering failed.
return print("Error: \(consentError.localizedDescription)")
}
// 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 controlador de visualização fornecido. O gerenciador de conclusão é chamado depois que o formulário é dispensado. Se o consentimento não for necessário, o gerenciador de conclusão será chamado imediatamente.
Criar um UIViewControllerRepresentable
Como loadAndPresentIfRequiredFromViewController:completionHandler:
requer um objeto UIViewController
, crie um tipo que esteja em conformidade com o
protocolo UIViewControllerRepresentable
. A função principal dele é expor uma referência UIViewController
para acesso
no SwiftUI.
struct FormViewControllerRepresentable: UIViewControllerRepresentable {
let viewController = UIViewController()
func makeUIViewController(context: Context) -> some UIViewController {
return viewController
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
}
Seu tipo ViewControllerRepresentable
não pode ter importância para o
conteúdo na tela, mas ainda precisa ser adicionado à hierarquia de visualização. Adicione-o
ao modificador de visualização
background(alignment:content:)
para que ele não ocupe espaço na tela.
struct ContentView: View {
@State private var hasViewAppeared = false
private let formViewControllerRepresentable = FormViewControllerRepresentable()
var body: some View {
VStack {
...
}
.background {
// Add the ViewControllerRepresentable to the background so it
// doesn't influence the placement of other views in the view hierarchy.
formViewControllerRepresentable
.frame(width: .zero, height: .zero)
}
.onAppear {
// Gather consent only the first time the view appears.
guard !hasViewAppeared else { return }
hasViewAppeared = true
// 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) {
(requestConsentError) in
if let consentError = requestConsentError {
// Consent gathering failed.
return print("Error: \(consentError.localizedDescription)")
}
UMPConsentForm.loadAndPresentIfRequired(from:
formViewControllerRepresentable.viewController) { loadAndPresentError in
if let consentError = loadAndPresentError {
// Consent gathering failed.
return print("Error: \(consentError.localizedDescription)")
}
// Consent gathering completed.
}
}
}
}
}
Solicitar anúncios
Antes de solicitar anúncios no seu app, verifique se você recebeu consentimento do usuário usando UMPConsentInformation.sharedInstance.canRequestAds
. Há duas instâncias a serem verificadas ao coletar o consentimento:
- Depois de receber o consentimento na sessão atual
- Imediatamente após ligar para
requestConsentInfoUpdateWithParameters:completionHandler:
É possível que o consentimento tenha sido obtido em uma 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 lançamento do app.
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.
struct ContentView: View {
@State private var isMobileAdsStartCalled = false
@State private var hasViewAppeared = false
private let formViewControllerRepresentable = FormViewControllerRepresentable()
var body: some View {
VStack {
...
}
.background {
// Add the ViewControllerRepresentable to the background so it
// doesn't influence the placement of other views in the view hierarchy.
formViewControllerRepresentable
.frame(width: .zero, height: .zero)
}
.onAppear {
// Gather consent only the first time the view appears.
guard !hasViewAppeared else { return }
hasViewAppeared = true
// 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) {
requestConsentError in
if let consentError = requestConsentError {
// Consent gathering failed.
return print("Error: \(consentError.localizedDescription)")
}
UMPConsentForm.loadAndPresentIfRequired(from:
formViewControllerRepresentable.viewController) { (loadAndPresentError) in
if let consentError = loadAndPresentError {
// Consent gathering failed.
return print("Error: \(consentError.localizedDescription)")
}
// Consent gathering completed.
if UMPConsentInformation.sharedInstance.canRequestAds {
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() {
guard !isMobileAdsStartCalled else { return }
isMobileAdsStartCalled = true
// Initialize the Google Mobile Ads SDK.
GADMobileAds.sharedInstance().start()
// TODO: Request an ad.
// GADInterstitialAd.load(...)
}
}