广告预加载(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

private func startPreloading(adUnitID: String) {
  // 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

- (void)startPreloadingWithAdUnitID:(nonnull NSString *)adUnitID {
  // 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: "ca-app-pub-3940256099942544/1712485313")
preloadConfig.bufferSize = 3

Objective-C

GADPreloadConfigurationV2 *preloadConfig =
    [[GADPreloadConfigurationV2 alloc] initWithAdUnitID:@"ca-app-pub-3940256099942544/1712485313"];
preloadConfig.bufferSize = 3;

预加载缓存限制

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

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