廣告預先載入 (Beta 版)

廣告預先載入是 Google Mobile Ads SDK 中由 Google 管理的廣告載入功能,可代您管理廣告載入和快取。如要預先載入廣告,您必須變更廣告載入的管理方式。如要使用廣告預先載入功能提升效能,請停用自訂快取,並將這項責任委派給 Google Mobile Ads SDK

相較於手動載入廣告,預先載入廣告具有下列優點:

  • 參照管理:保留已載入的廣告,因此您不必維護參照,直到準備好顯示廣告為止。
  • 自動重新載入:從快取中取出廣告時,系統會自動載入新廣告。
  • 管理重試:使用指數輪詢自動重試失敗的要求。
  • 到期處理:在廣告到期前 (通常是一小時後) 自動重新整理廣告。
  • 快取最佳化:如果使用的快取大小超過一,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。