SDK-Integration in SwiftUI

In diesem Leitfaden erfahren Sie, wie Sie die Informationen zur Einwilligung der Nutzer über ein Einwilligungsformular einholen und dann die Einwilligung der Nutzer einholen, wenn Sie Anzeigen mit dem User Messaging Platform (UMP) SDK in einer SwiftUI-App anfordern.

Voraussetzungen

Sie sollten mit requestConsentInfoUpdateWithParameters:completionHandler:bei jedem Start der App eine Aktualisierung der Einwilligungsinformationen des Nutzers anfordern. So wird festgelegt, ob Nutzer ihre Einwilligung geben müssen, falls sie dies noch nicht getan haben oder ob sie abgelaufen ist.

Das folgende Beispiel zeigt, wie der Status von einem View in der Methode onAppear(perform:) geprüft wird.

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

Einwilligungsformular laden und präsentieren, falls erforderlich

Nachdem Sie den aktuellen Einwilligungsstatus erhalten haben, rufen SieloadAndPresentIfRequiredFromViewController:completionHandler: in der KlasseUMPConsentForm auf, um ein Einwilligungsformular zu laden. Wenn der Einwilligungsstatus erforderlich ist, lädt das SDK ein Formular und zeigt es sofort über den bereitgestellten Ansichts-Controller an. Der Abschluss-Handler wird aufgerufen, nachdem das Formular geschlossen wurde. Wenn keine Einwilligung erforderlich ist, wird der Abschluss-Handler sofort aufgerufen.

UIViewControllerRepresentable erstellen

Da loadAndPresentIfRequiredFromViewController:completionHandler: ein UIViewController-Objekt erfordert, erstellen Sie einen Typ, der dem UIViewControllerRepresentable-Protokoll entspricht. Seine Hauptaufgabe besteht darin, eine UIViewController-Referenz für den Zugriff in SwiftUI zur Verfügung zu stellen.

struct FormViewControllerRepresentable: UIViewControllerRepresentable {
  let viewController = UIViewController()

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

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

Der Typ ViewControllerRepresentable sollte für den Inhalt auf dem Bildschirm keine Bedeutung haben, muss aber dennoch der Ansichtshierarchie hinzugefügt werden. Fügen Sie ihn im Ansichtsmodifikator background(alignment:content:) hinzu, damit er keinen Platz auf dem Bildschirm einnimmt.

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

Anzeigenanfrage senden

Bevor Sie in Ihrer App Anzeigen anfordern, prüfen Sie, ob Sie über UMPConsentInformation.sharedInstance.canRequestAdsdie Einwilligung des Nutzers eingeholt haben. Beim Einholen der Einwilligung müssen zwei Fälle überprüft werden:

  1. Nachdem die Einwilligung in der aktuellen Sitzung eingeholt wurde
  2. Sofort nach dem Anruf bei requestConsentInfoUpdateWithParameters:completionHandler:

Möglicherweise wurde die Einwilligung bereits in einer früheren Sitzung eingeholt. Als Best Practice für die Latenz sollten Sie nicht warten, bis der Callback abgeschlossen ist. So können Sie die Anzeigen so schnell wie möglich nach dem Start Ihrer App laden.

Falls beim Einholen der Einwilligung ein Fehler auftritt, sollten Sie trotzdem versuchen, Anzeigen anzufordern. Das UMP SDK verwendet den Einwilligungsstatus aus der vorherigen Sitzung.

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