Интеграция SDK со SwiftUI

В этом руководстве показано, как запросить информацию о согласии пользователя через форму согласия, а затем проверить согласие пользователя при запросе рекламы с помощью SDK платформы обмена сообщениями пользователей (UMP) в приложении SwiftUI.

Предварительные условия

Вам следует запрашивать обновление информации о согласии пользователя при каждом запуске приложения, используя requestConsentInfoUpdateWithParameters:completionHandler:. Это определяет, должен ли ваш пользователь предоставить согласие, если он еще этого не сделал, или срок действия его согласия истек.

Вот пример того, как проверить статус из View в методе 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.
      }
    }
  }
}

Загрузите и предоставьте форму согласия, если требуется.

После получения последней версии статуса согласия вызовитеloadAndPresentIfRequiredFromViewController:completionHandler: в классеUMPConsentForm , чтобы загрузить форму согласия. Если требуется статус согласия, SDK загружает форму и немедленно представляет ее из предоставленного контроллера представления. Обработчик завершения вызывается после закрытия формы. Если согласие не требуется, обработчик завершения вызывается немедленно.

Создайте UIViewControllerRepresentable.

Поскольку для loadAndPresentIfRequiredFromViewController:completionHandler: требуется объект UIViewController , создайте тип, соответствующий протоколу UIViewControllerRepresentable . Его основная задача — предоставить ссылку UIViewController для доступа в SwiftUI.

struct FormViewControllerRepresentable: UIViewControllerRepresentable {
  let viewController = UIViewController()

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

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

Тип ViewControllerRepresentable не должен иметь никакого значения для содержимого на экране, но его все равно необходимо добавить в иерархию представлений. Добавьте его в background(alignment:content:) чтобы он не занимал пространство экрана.

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

Запросить рекламу

Прежде чем запрашивать рекламу в своем приложении, проверьте, получили ли вы согласие от пользователя с помощью UMPConsentInformation.sharedInstance.canRequestAds. При получении согласия необходимо проверить два момента:

  1. После получения согласия в текущем сеансе
  2. Сразу после вызова requestConsentInfoUpdateWithParameters:completionHandler:

Возможно, согласие было получено на предыдущем сеансе. В целях снижения задержки мы рекомендуем не дожидаться завершения обратного вызова, чтобы вы могли начать загрузку рекламы как можно скорее после запуска приложения.

Если в процессе сбора согласия возникает ошибка, вам все равно следует попытаться запросить рекламу. UMP SDK использует статус согласия из предыдущего сеанса.

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