广告预加载(Beta 版)

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

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

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

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

前提条件

在继续学习本教程之前,您必须设置 Google Mobile Ads SDK。

开始预加载广告

应用启动时,调用 preload 方法一次。调用 preload 方法后,Google Mobile Ads SDK 会自动预加载广告,并重试预加载配置的失败请求。

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

Swift

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

Objective-C

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

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

获取并展示预加载的广告

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

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

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

Swift

private func showInterstitialAd(adUnitID: String) {
  // Verify that the preloaded ad is available before polling.
  guard isInterstitialAvailable(adUnitID: adUnitID) else {
    print("Preloaded interstitial ad is not available.")
    return
  }

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

  // 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)showInterstitialAdWithAdUnitID:(nonnull NSString *)adUnitID {
  // Verify that the preloaded ad is available before polling.
  if (![self isInterstitialAvailableWithAdUnitID:adUnitID]) {
    NSLog(@"Preloaded interstitial ad is not available.");
    return;
  }

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

  // 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 getInterstitialAdResponseInfo(preloadID: String) {
  // Get the response info for the preloaded ad.
  if let responseInfo = InterstitialAdPreloader.shared.responseInfo(
    with: preloadID)
  {
    print("Ad response ID: \(responseInfo.responseIdentifier ?? "")")
  }
}

Objective-C

- (void)getInterstitialAdResponseInfoWithPreloadID:(nonnull NSString *)preloadID {
  // Get the response info for the preloaded ad.
  GADResponseInfo *responseInfo =
      [GADInterstitialAdPreloader.sharedInstance
          adResponseInfoWithPreloadID:preloadID];
  if (responseInfo) {
    NSLog(@"Ad response ID: %@", responseInfo.responseIdentifier);
  }
}

检查预加载广告的可用性

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

获取预加载广告的可用性

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

Swift

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

Objective-C

- (BOOL)isInterstitialAvailableWithAdUnitID:(nonnull NSString *)adUnitID {
  // Verify that an ad is available before polling.
  return [GADInterstitialAdPreloader.sharedInstance isAdAvailableWithPreloadID:adUnitID];
}

监听预加载广告的可用性

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

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

  • 不要调用 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.
  // Don't call InterstitialAdPreloader.shared.preload or
  // InterstitialAdPreloader.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.
  // 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。如需停止所有预加载器的预加载,请调用 stopPreloadingAndRemoveAllAds。

设置缓冲区大小

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

Swift

let preloadConfig = PreloadConfigurationV2(adUnitID: adUnitID)
// Define a PreloadConfiguration and set the buffer size to 2 preloaded ads.
preloadConfig.bufferSize = 2

Objective-C

GADPreloadConfigurationV2 *preloadConfig =
    [[GADPreloadConfigurationV2 alloc] initWithAdUnitID:adUnitID];
// Define a PreloadConfiguration and set the buffer size to 2 preloaded ads.
preloadConfig.bufferSize = 2;

预加载缓存限制

Google Mobile Ads SDK 会针对所有广告单元和预加载 ID 强制执行应用范围的预加载广告总数限制:

  • 默认限制:Google Mobile Ads SDK 最多可在内存中保存 6 个预加载的广告。此限制适用于所有格式和预加载 ID。
  • 建议为每个预加载 ID 保留 2 的缓冲区空间。