广告预加载(Alpha 版)

广告预加载是 Google Mobile Ads SDK 中的一项由 Google 管理的广告加载功能,可代表您管理广告加载和缓存。广告预加载需要您更改管理广告加载的方式。如需使用广告预加载来优化性能,请停用自定义缓存并将该责任委托给 Google Mobile Ads SDK

与手动加载广告相比,广告预加载具有以下优势:

  • 引用管理:用于保存已加载的广告,这样您就不必维护引用,直到准备好展示广告为止。
  • 自动重新加载:当您从缓存中拉取广告时,系统会自动加载新广告。
  • 受管理的重试:使用指数退避算法自动重试失败的请求。
  • 过期处理:在广告过期之前(通常为一小时后)自动刷新广告。
  • 缓存优化:如果您使用的缓存大小大于 1,Google Mobile Ads SDK 会优化缓存顺序,以投放效果最佳的广告。

本指南介绍了如何配置预加载广告、检查预加载广告的可用性以及展示预加载的广告。

前提条件

在继续学习本教程之前,您需要完成以下事项:

  • 安装 Google Mobile Ads SDK 12.6.0 版或更高版本。 您可以在 11.12.0 - 12.2.0 中找到旧版的相关开发者资源,但我们建议您使用 12.6.0 或更高版本,并遵循本指南中的说明。
  • 设置 Google Mobile Ads SDK

开始预加载广告

如需开始预加载广告,请调用 preload()。在应用启动时仅调用此方法一次。调用 preload() 后,Google Mobile Ads SDK 会自动预加载广告,并重试预加载配置的失败请求。

以下示例开始预加载广告:

Swift

// Start the preloading initialization process.
let request = Request()
let interstitialConfig = PreloadConfigurationV2(
  adUnitID: Constants.interstitialAdUnitID, request: request)
InterstitialAdPreloader.shared.preload(
  for: Constants.interstitialAdUnitID, configuration: interstitialConfig, delegate: self)

Objective-C

// Start the preloading initialization process.
GADRequest *request = [GADRequest request];
GADPreloadConfigurationV2 *interstitialConfig = [[GADPreloadConfigurationV2 alloc] initWithAdUnitID:interstitialAdUnitID request:request];

[GADInterstitialAdPreloader.sharedInstance preloadForPreloadID:interstitialAdUnitID
                                                     configuration:interstitialConfig
                                                          delegate:self];

获取并展示预加载的广告

使用广告预加载时,Google Mobile Ads SDK 会保存缓存的广告。 当您想展示广告时,请调用 adWithPreloadID()Google Mobile Ads SDK 会检索可用的广告,并在后台自动预加载下一个广告。

在您准备好展示广告之前,请避免调用此方法。将广告保留在缓存中可让 Google Mobile Ads SDK 自动刷新已过期的广告并执行缓存优化。

以下示例检索并展示了预加载的广告:

Swift

private func showInterstitialAd() {
  // Verify that the preloaded ad is available before polling.
  guard isInterstitialAvailable() else {
    printAndShowAlert("Preload interstitial ad is exhausted.")
    return
  }

  // Polling returns the next available ad and load another ad in the background.
  let ad = InterstitialAdPreloader.shared.ad(with: Constants.interstitialAdUnitID)

  // Interact with the ad object as needed.
  print("Interstitial ad response info: \(String(describing: ad?.responseInfo))")
  ad?.paidEventHandler = { (value: AdValue) in
    print("Interstitial ad paid event: \(value.value), \(value.currencyCode)")
  }

  ad?.fullScreenContentDelegate = self
  ad?.present(from: self)
}

Objective-C

- (void)showInterstitialAd {
  // Verify that the preloaded ad is available before polling.
  if (![self isInterstitialAvailable]) {
    [self logAndShowAlert:@"Preloaded interstitial ad is not available."];
    return;
  }

  // Getting the preloaded ad loads another ad in the background.
  GADInterstitialAd *ad = [GADInterstitialAdPreloader.sharedInstance adWithPreloadID:interstitialAdUnitID];

  // Interact with the ad object as needed.
  NSLog(@"Interstitial ad response info: %@", ad.responseInfo);
  ad.paidEventHandler = ^(GADAdValue *_Nonnull value) {
    NSLog(@"Interstitial ad paid event: %@ %@ ", value.value, value.currencyCode);
  };
  ad.fullScreenContentDelegate = self;
  [ad presentFromRootViewController:self];
}

检查预加载广告的可用性

如需检查广告投放情况,请选择以下选项之一:

获取预加载广告的可用性

以下示例检查了广告是否可用:

Swift

private func isInterstitialAvailable() -> Bool {
  // Verify that an ad is available before polling.
  return InterstitialAdPreloader.shared.isAdAvailable(with: Constants.interstitialAdUnitID)
}

Objective-C

- (BOOL)isInterstitialAvailable {
  // Verify that an ad is available before polling.
  return [GADInterstitialAdPreloader.sharedInstance isAdAvailableWithPreloadID:(interstitialAdUnitID)];
}

监听预加载广告的可用性

注册预加载事件,以便在广告预加载成功、预加载失败或广告缓存耗尽时收到通知。

预加载事件旨在用于分析。在预加载事件回调中:

  • 不要调用 preload()
  • 除非广告会立即展示,否则请避免调用 adWithPreloadID()

以下示例注册了广告事件:

Swift

func adAvailable(forPreloadID preloadID: String, responseInfo: ResponseInfo) {
  // This callback indicates that an ad is available for the specified configuration.
  // No action is required here, but updating the UI can be useful in some cases.
  print("Ad preloaded successfully for ad preload ID: \(preloadID)")
  // ...
}

func adsExhausted(forPreloadID preloadID: String) {
  // This callback indicates that all the ads for the specified configuration have been
  // consumed and no ads are available to show. No action is required here, but updating
  // the UI can be useful in some cases.
  // [Important] Don't call AdPreloader.shared.preload or AdPreloader.shared.ad
  // from adsExhausted.
  print("Ad exhausted for ad preload ID: \(preloadID)")
  // ...
}

func adFailedToPreload(forPreloadID preloadID: String, error: Error) {
  print(
    "Ad failed to load with ad preload ID: \(preloadID), Error: \(error.localizedDescription)"
  )
}

Objective-C

- (void)adAvailableForPreloadID:(nonnull NSString *)preloadID responseInfo:(nonnull GADResponseInfo *)responseInfo {
  // This callback indicates that an ad is available for the specified configuration.
  // No action is required here, but updating the UI can be useful in some cases.
  NSLog(@"Ad preloaded successfully for ad unit ID: %@", preloadID);
  // ...
}

- (void)adsExhaustedForPreloadID:(nonnull NSString  *)preloadID {
  // This callback indicates that all the ads for the specified configuration have been
  // consumed and no ads are available to show. No action is required here, but updating
  // the UI can be useful in some cases.
  // [Important] Don't call [GAD<Format>AdPreloader preloadForPreloadID:] or
  // [GAD<Format>AdPreloader adWithPreloadID:] from adsExhaustedForPreloadID.
  NSLog(@"Ad exhausted for ad preload ID: %@", preloadID);
  // ...
}

- (void)adFailedToPreloadForPreloadID:(nonnull NSString  *)preloadID error:(nonnull NSError *)error {
  NSLog(@"Ad failed to load with ad preload ID: %@, Error: %@", preloadID, error.localizedDescription);
}

停止预加载广告

如果您不需要在会话中再次显示预加载 ID 的广告,可以停止预加载广告。如需停止预加载特定预加载 ID 的广告,请使用预加载 ID 调用 stopPreloadingAndRemoveAdsForPreloadID()

设置缓冲区空间

缓冲区空间用于控制内存中预加载的广告数量。默认情况下,Google 会优化缓冲区空间大小,以平衡内存消耗和广告投放延迟时间。如果您的应用在加载下一个广告之前展示广告,您可以设置自定义缓冲区空间,以增加内存中保留的广告数量。我们建议缓冲区大小不超过 4。

Swift

let preloadConfig = PreloadConfigurationV2(adUnitID: "/21775744923/example/rewarded")
preloadConfig.bufferSize = 3

Objective-C

GADPreloadConfigurationV2 *preloadConfig =
    [[GADPreloadConfigurationV2 alloc] initWithAdUnitID:@"/21775744923/example/rewarded"];
preloadConfig.bufferSize = 3;