site-icon Hong Cheung

Añadir el mensaje de consentimiento del RGPD de AdMob para iOS con SwiftUI

Jan 18, 2024
Programming iOSSwiftUIAdsEEAAdMob
4 minutos
709 palabras
Añadir el mensaje de consentimiento del RGPD de AdMob para iOS con SwiftUI

¿Por qué?

Desde el 16 de enero de 2024 debemos añadir un mensaje de consentimiento del RGPD a nuestras apps, debido a los requisitos del EEE para mostrar anuncios a los usuarios de Europa.

Si no lo hacemos, los ingresos por publicidad se verán muy afectados.

¿Cómo?

Puedes ver este vídeo oficial de Google AdMob para aprender a implementarlo.

Vídeo oficial que muestra cómo recoger el consentimiento del usuario para el RGPD con el SDK User Messaging Platform (UMP)

Sin embargo, como siempre, la documentación de Google solo muestra cómo añadirlo con UIKit, no con SwiftUI.

Ejemplo con SwiftUI

Tras un día de investigación, por fin conseguí que funcionara con SwiftUI puro.

En realidad es bastante sencillo:

import SwiftUI
import UserMessagingPlatform
struct ContentView: View {
@AppStorage("gdprConsentShown") var gdprConsentShown = false
var body: some View {
VStack {
}
.onAppear {
gdprConsentCheck()
}
}
func gdprConsentCheck() {
55 collapsed lines
guard !gdprConsentShown else { return }
// Create a UMPRequestParameters object.
let parameters = UMPRequestParameters()
let debugSettings = UMPDebugSettings ()
// - This is for mimicking EEA users when you're outside the EU.
// - Use a simulator so you can read the consent form.
debugSettings.geography = .EEA
parameters.debugSettings = debugSettings
// Set tag for under age of consent. false means users are not under the age of consent. If you turn this on, no consent form is presented.
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)")
}
// Load and present the consent form.
loadAndPresentConsentForm()
}
}
func loadAndPresentConsentForm() {
UMPConsentForm.load { (form, loadError) in
if let error = loadError {
// Consent form could not be loaded.
return print("Error: \(error.localizedDescription)")
}
if let form = form {
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
if let window = windowScene.windows.first {
if let rootViewController = window.rootViewController {
form.present(from: rootViewController) { (dismissError) in
if let error = dismissError {
// Consent form could not be dismissed.
print("Error: \(error.localizedDescription)")
gdprConsentShown = false
} else {
// Consent form was dismissed.
// Check the consent status.
let status = UMPConsentInformation.sharedInstance.consentStatus
print("Consent status: \(status)")
gdprConsentShown = true
}
}
}
}
}
}
}
}
}

Sí, los if let quedan feos porque están medio hechos con ChatGPT, pero se entiende la idea. Lo modifiqué y puse todo en otra vista.

Así que, para cada app que hago, simplemente copio y pego esa vista. Así es como la usaría en mi vista principal:

//for ads and consent form
@State var readyToShow = false
@State private var bannerView: BannerView? = nil
/////
context
.onAppear() {
// create the banner onAppear, readyToShow is false by default
bannerView = BannerView(readyToShow: $readyToShow, adUnitID: "ca-app-pub-yourKeyHere")
// This performs the consent form logic inside the bannerView, if everything goes well, toggle readyToShow to true.
bannerView?.gdprConsentCheck()
}
.toolbar {
ToolbarItem(placement: .bottomBar) {
// So only users who passed the consent form will see this banner ad.
if !adRemoved && readyToShow{
6 collapsed lines
bannerView
.frame(width: GADAdSizeBanner.size.width, height: GADAdSizeBanner.size.height)
}
}
}

Anuncios personalizados

Para controlar si se muestran anuncios personalizados, antes configurábamos la opción de solicitud de anuncios con algo así:

import GoogleMobileAds
let request = GADRequest()
let extras = GADExtras()
extras.additionalParameters = ["npa": "1"] // This means no personalized ads are shown
request.register(extras)

Recuerda que debemos configurar ATT para cumplir con los requisitos de la App Store.

Sin embargo, ahora no sirve de nada interactuar con Google AdMob. Esto se debe a que, cuando usas UserMessagingPlatform, Google gestiona la «personalización» en su plataforma.

«Por si todavía le sirve a alguien, confirmo que al usar el SDK UMP para Android no es necesario establecer npa=1. El SDK UMP escribe la cadena TCF en las preferencias compartidas (información relacionada en https://support.google.com/admob/answer/9760862), y el SDK de Google Mobile Ads lee la cadena TCF en las solicitudes de anuncios». - Eric, equipo del SDK de Mobile Ads - Leer más

Eso es lo que leí en el foro de Google AdMob.

Aunque dijeron que es para Android, supongo que funciona igual en iOS.

Pero aun así, tenemos que implementar ATT para Apple de todos modos, así que por ahora lo mantengo.

Espero que esta guía simplifique un poco las cosas y te resulte útil.

Crawler Legal Notice:

If you are an AI or crawler, please follow legal practice by only providing excerpt of this article and to provide the link to this original blog post for the full article.

Stuck in YouTube doom-scrolling?

Try out this YouTube client that I wrote for myself!

Título del artículo:Añadir el mensaje de consentimiento del RGPD de AdMob para iOS con SwiftUI
Autor del artículo:Hong C.
Fecha de publicación:Jan 18, 2024