Tích hợp SDK với SwiftUI

Hướng dẫn này cho biết cách yêu cầu thông tin về sự đồng ý của người dùng thông qua biểu mẫu lấy sự đồng ý, sau đó kiểm tra sự đồng ý của người dùng khi yêu cầu quảng cáo bằng SDK Nền tảng thông báo cho người dùng (UMP) trong ứng dụng SwiftUI.

Điều kiện tiên quyết

Bạn nên yêu cầu cập nhật thông tin về trạng thái đồng ý của người dùng mỗi lần chạy ứng dụng, bằng cách sử dụng requestConsentInfoUpdateWithParameters:completionHandler:. Chế độ này xác định liệu người dùng của bạn có cần phải đưa ra sự đồng ý nếu họ chưa làm vậy hay nếu trạng thái đồng ý của họ đã hết hạn.

Dưới đây là ví dụ về cách kiểm tra trạng thái từ View trong phương thức 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.
      }
    }
  }
}

Tải và trình bày biểu mẫu đồng ý (nếu bắt buộc)

Sau khi bạn nhận được trạng thái đồng ý mới nhất, hãy gọi loadAndPresentIfRequiredFromViewController:completionHandler: trên lớp UMPConsentForm để tải biểu mẫu lấy sự đồng ý. Nếu trạng thái đồng ý là bắt buộc, SDK sẽ tải một biểu mẫu và hiển thị ngay biểu mẫu đó từ trình kiểm soát khung hiển thị được cung cấp. Trình xử lý hoàn thành được gọi sau khi biểu mẫu bị đóng. Nếu không cần phải có sự đồng ý, trình xử lý hoàn thành sẽ được gọi ngay lập tức.

Tạo UIViewControllerRepresentable

loadAndPresentIfRequiredFromViewController:completionHandler: đòi hỏi phải có đối tượng UIViewController, hãy tạo một loại phù hợp với giao thức UIViewControllerRepresentable. Nhiệm vụ chính của lớp này là hiển thị một tham chiếu UIViewController để truy cập trong SwiftUI.

struct FormViewControllerRepresentable: UIViewControllerRepresentable {
  let viewController = UIViewController()

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

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

Loại ViewControllerRepresentable không nên có ý nghĩa gì đối với nội dung trên màn hình, nhưng vẫn cần được thêm vào hệ phân cấp khung hiển thị. Hãy thêm phương thức này vào đối tượng sửa đổi khung hiển thị background(alignment:content:) để không chiếm diện tích màn hình.

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

Yêu cầu quảng cáo

Trước khi yêu cầu quảng cáo trong ứng dụng của bạn, hãy kiểm tra xem bạn đã nhận được sự đồng ý của người dùng sử dụng UMPConsentInformation.sharedInstance.canRequestAdshay chưa. Có hai trường hợp cần kiểm tra trong quá trình thu thập sự đồng ý:

  1. Sau khi thu thập sự đồng ý trong phiên hiện tại
  2. Ngay sau khi bạn gọi điện requestConsentInfoUpdateWithParameters:completionHandler:

Có thể người dùng đã đồng ý trong phiên trước đó. Một phương pháp hay nhất về độ trễ là bạn không nên đợi lệnh gọi lại hoàn tất để có thể bắt đầu tải quảng cáo càng sớm càng tốt sau khi ứng dụng khởi chạy.

Nếu xảy ra lỗi trong quá trình thu thập sự đồng ý, bạn vẫn nên tìm cách yêu cầu quảng cáo. SDK UMP sử dụng trạng thái đồng ý của phiên hoạt động trước đó.

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