Integracja pakietu SDK z SwiftUI

Z tego przewodnika dowiesz się, jak uzyskać informacje o zgodzie użytkownika za pomocą formularza zgody, a następnie sprawdzić tę zgodę w przypadku wysyłania żądań reklam za pomocą pakietu SDK User Messaging Platform (UMP) w aplikacji SwiftUI.

Wymagania wstępne

Za pomocą requestConsentInfoUpdateWithParameters:completionHandler:należy aktualizować informacje o zgodzie użytkownika przy każdym uruchomieniu aplikacji. Określa to, czy użytkownik musi wyrazić zgodę, jeśli jeszcze tego nie zrobił, czy też jej zgoda wygasła.

Oto przykład, jak sprawdzić stan z elementu View w metodzie 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.
      }
    }
  }
}

Wczytaj i wyświetl formularz zgody, jeśli jest to wymagane

Gdy otrzymasz najbardziej aktualny stan zgody, wywołajloadAndPresentIfRequiredFromViewController:completionHandler: na zajęciachUMPConsentForm , aby wczytać formularz zgody. Jeśli stan zgody jest wymagany, pakiet SDK wczytuje formularz i od razu wyświetla go z kontrolera widoków danych. Moduł obsługi wypełniania jest wywoływany po zamknięciu formularza. Jeśli zgoda nie jest wymagana, moduł obsługi zakończenia zostanie natychmiast wywołany.

Tworzenie obiektu UIViewControllerRepresentable

Ponieważ loadAndPresentIfRequiredFromViewController:completionHandler: wymaga obiektu UIViewController, utwórz typ zgodny z protokołem UIViewControllerRepresentable. Jego głównym zadaniem jest udostępnienie odwołania do UIViewController na potrzeby dostępu w SwiftUI.

struct FormViewControllerRepresentable: UIViewControllerRepresentable {
  let viewController = UIViewController()

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

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

Typ ViewControllerRepresentable nie powinien mieć żadnego znaczenia dla treści na ekranie, ale nadal musi zostać dodany do hierarchii widoków. Dodaj go w ramach modyfikatora widoku background(alignment:content:), aby nie zajmował miejsca na ekranie.

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

Wyślij żądanie

Zanim poprosisz o wyświetlenie reklam w aplikacji, sprawdź, czy masz zgodę użytkownika korzystającego z usługi UMPConsentInformation.sharedInstance.canRequestAds. Proces uzyskiwania zgody należy sprawdzić w 2 przypadkach:

  1. Po uzyskaniu zgody użytkownika w bieżącej sesji
  2. Zaraz po nadzwonieniu do: requestConsentInfoUpdateWithParameters:completionHandler:

Możliwe, że zgoda została uzyskana w poprzedniej sesji. Ze względu na czas oczekiwania zalecamy nie czekanie na zakończenie wywołania zwrotnego, ponieważ pozwoli to rozpocząć ładowanie reklam od razu po uruchomieniu aplikacji.

Jeśli podczas uzyskiwania zgody użytkowników wystąpi błąd, nadal wysyłaj żądania reklam. Pakiet UMP SDK korzysta ze stanu zgody z poprzedniej sesji.

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