Integración del SDK con SwiftUI

En esta guía, se muestra cómo solicitar información de consentimiento del usuario a través de un formulario de consentimiento y, luego, verificar el consentimiento del usuario cuando se solicitan anuncios con el SDK de User Messaging Platform (UMP) en una app de SwiftUI.

Requisitos previos

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ó.

A continuación, se muestra un ejemplo de cómo verificar el estado de un View en el 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.
      }
    }
  }
}

Cargar y presentar un formulario de consentimiento si es necesario

Una vez que recibas 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 controlador de vista proporcionado. Se llama al controlador de finalización después de que se descarta el formulario. Si no se requiere consentimiento, se llama al controlador de finalización de inmediato.

Cómo crear un UIViewControllerRepresentable

Debido a que loadAndPresentIfRequiredFromViewController:completionHandler: requiere un objeto UIViewController, crea un tipo que cumpla con el protocolo UIViewControllerRepresentable. Su trabajo principal es exponer una referencia de UIViewController para acceder en SwiftUI.

struct FormViewControllerRepresentable: UIViewControllerRepresentable {
  let viewController = UIViewController()

  func makeUIViewController(context: Context) -> some UIViewController {
    return viewController
  }

  func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
}

El tipo ViewControllerRepresentable no debe tener importancia para el contenido en pantalla, pero se debe agregar a la jerarquía de vistas. Agrégalo dentro del modificador de vista background(alignment:content:) para que no ocupe espacio en la pantalla.

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 anuncios

Antes de solicitar anuncios en tu app, verifica si obtuviste el consentimiento del usuario mediante UMPConsentInformation.sharedInstance.canRequestAds. Hay dos instancias que debes verificar cuando obtienes el consentimiento:

  1. Después de obtener el consentimiento en la sesión actual
  2. Inmediatamente después de llamar a requestConsentInfoUpdateWithParameters:completionHandler:

Es posible que se haya obtenido el consentimiento en una sesión anterior. Como práctica recomendada para la latencia, sugerimos no esperar a que se complete la devolución de llamada para que puedas comenzar a cargar anuncios lo antes posible después de que se inicie la 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.

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(...)
  }
}