SwiftUI ile SDK entegrasyonu

Bu kılavuzda, rıza formu aracılığıyla kullanıcı rızası bilgilerinin nasıl isteneceği ve ardından SwiftUI uygulamasında Kullanıcı Mesajlaşma Platformu (UMP) SDK'sı ile reklam isterken kullanıcı rızasının nasıl kontrol edileceği gösterilmektedir.

Ön koşullar

requestConsentInfoUpdateWithParameters:completionHandler:kullanarak her uygulama başlatmada kullanıcının izin bilgilerinin güncellenmesini istemelisiniz. Bu, kullanıcınızın henüz yapmadıysa izin vermesi gerekip gerekmediğini veya izin süresinin dolup dolmadığını belirler.

onAppear(perform:) yöntemindeki bir View üzerinden durumu nasıl kontrol edeceğinizle ilgili örneği aşağıda bulabilirsiniz.

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

Gerekirse izin formu yükleme ve gösterme

En güncel izin durumunu aldıktan sonra izin formu yüklemek içinUMPConsentForm sınıfıloadAndPresentIfRequiredFromViewController:completionHandler: arayın. İzin durumu gerekiyorsa SDK bir form yükler ve sağlanan görüntüleme denetleyicisinden hemen sunar. Tamamlama işleyicisi, form kapatıldıktan sonra çağrılır. İzin gerekmiyorsa tamamlama işleyici hemen çağrılır.

UIViewControllerRepresentable oluşturma

loadAndPresentIfRequiredFromViewController:completionHandler:, UIViewController nesnesi gerektirdiğinden UIViewControllerRepresentable protokolüne uygun bir tür oluşturun. Birincil işi, SwiftUI'da erişim için bir UIViewController referansı sunmaktır.

struct FormViewControllerRepresentable: UIViewControllerRepresentable {
  let viewController = UIViewController()

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

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

ViewControllerRepresentable türünüzün ekrandaki içerik için herhangi bir önemi olmamasına rağmen yine de görünüm hiyerarşisine eklenmesi gerekir. Ekran alanını kaplamaması için bunu görünüm değiştiriciye background(alignment:content:) ekleyin.

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

Reklam isteğinde bulun

Uygulamanızda reklam isteğinde bulunmadan önce, UMPConsentInformation.sharedInstance.canRequestAdsözelliğini kullanarak kullanıcıdan izin alıp almadığınızı kontrol edin. İzin toplarken kontrol edilecek iki örnek vardır:

  1. Mevcut oturumda izin toplandıktan sonra
  2. requestConsentInfoUpdateWithParameters:completionHandler:adlı kişiyi aradıktan hemen sonra

Önceki bir oturumda izin alınmış olabilir. Gecikmeye yönelik en iyi uygulama olarak, geri çağırmanın tamamlanmasını beklememenizi öneririz. Böylece uygulamanız kullanıma sunulduktan sonra mümkün olan en kısa sürede reklam yüklemeye başlayabilirsiniz.

İzin toplama sürecinde bir hata oluşursa yine de reklam istemeyi deneyebilirsiniz. UMP SDK'sı önceki oturumdaki izin durumunu kullanır.

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