Integrazione dell'SDK con SwiftUI

Questa guida mostra come richiedere le informazioni sul consenso degli utenti tramite un modulo di consenso e come controllare il consenso degli utenti quando si richiedono annunci con l'SDK UMP (User Messaging Platform) in un'app SwiftUI.

Prerequisiti

Devi richiedere un aggiornamento delle informazioni sul consenso dell'utente a ogni lancio dell'app, utilizzando requestConsentInfoUpdateWithParameters:completionHandler:. Questo determina se l'utente deve dare il consenso nel caso in cui non l'abbia già fatto o se il consenso è scaduto.

Ecco un esempio di come controllare lo stato da un elemento View nel metodo 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.
      }
    }
  }
}

Carica e presenta un modulo di consenso, se necessario

Dopo aver ricevuto lo stato del consenso più aggiornato, chiama loadAndPresentIfRequiredFromViewController:completionHandler: il UMPConsentForm corso per caricare un modulo di consenso. Se lo stato del consenso è obbligatorio, l'SDK carica un modulo e lo presenta immediatamente dal controller di visualizzazione fornito. Il gestore del completamento viene richiamato dopo che il modulo viene ignorato. Se il consenso non è richiesto, il gestore del completamento viene chiamato immediatamente.

Crea un UIViewControllerRepresentable

Poiché loadAndPresentIfRequiredFromViewController:completionHandler: richiede un oggetto UIViewController, crea un tipo che sia conforme al protocollo UIViewControllerRepresentable. Il suo compito principale è esporre un riferimento UIViewController per l'accesso in SwiftUI.

struct FormViewControllerRepresentable: UIViewControllerRepresentable {
  let viewController = UIViewController()

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

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

Il tipo ViewControllerRepresentable non dovrebbe avere alcuna rilevanza per i contenuti sullo schermo, ma deve comunque essere aggiunto alla gerarchia delle visualizzazioni. Aggiungilo all'interno del modificatore di visualizzazione background(alignment:content:) in modo che non occupi spazio sullo schermo.

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

Richiedi annunci

Prima di richiedere annunci nella tua app, controlla di aver ottenuto il consenso da parte dell'utente utilizzando UMPConsentInformation.sharedInstance.canRequestAds. Esistono due istanze da controllare durante la raccolta del consenso:

  1. Dopo aver raccolto il consenso nella sessione corrente
  2. Subito dopo aver chiamato requestConsentInfoUpdateWithParameters:completionHandler:

È possibile che il consenso sia stato ottenuto in una sessione precedente. Come best practice in materia di latenza, ti consigliamo di non attendere il completamento del callback in modo da poter iniziare a caricare gli annunci il prima possibile dopo l'avvio dell'app.

Se si verifica un errore durante la procedura di raccolta del consenso, devi comunque provare a richiedere gli annunci. L'SDK UMP utilizza lo stato del consenso della sessione precedente.

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