載入單一插頁式獎勵廣告

插頁式獎勵廣告會在畫面或遊戲關卡之間顯示,並提供應用程式內商品做為獎勵。與獎勵廣告不同的是,使用者不需選擇觀看即可看到廣告。 詳情請參閱「插頁式獎勵廣告單元總覽」。

本指南說明如何將插頁式獎勵廣告整合至 React Native 應用程式。

必要條件

請先完成下列事項,再繼續操作:

僅適用於搭載 Android

ca-app-pub-3940256099942544/5354046379

iOS

ca-app-pub-3940256099942544/6978759866

載入廣告

如要載入插頁式獎勵廣告,請呼叫 RewardedInterstitialAd 類別的 load 方法。

以下範例會在成功時載入插頁式獎勵廣告,失敗時則記錄錯誤:

export async function loadRewardedInterstitialAd(
  adUnitId: string,
): Promise<RewardedInterstitialAd | null> {
  try {
    const ad = await RewardedInterstitialAd.load({adUnitId});
    return ad;
  } catch (error) {
    const loadError = error as LoadAdError;
    console.error('Failed to load rewarded interstitial:', loadError.message);
    return null;
  }
}

監聽廣告事件

顯示廣告前,請在載入的 RewardedInterstitialAd 執行個體上設定 adEventCallback 監聽器。這個事件監聽器會接收廣告生命週期事件的回呼,例如廣告顯示在畫面上,或使用者輕觸廣告。如要查看可用的回呼,請參閱 AdEventCallback。

以下範例設定了回呼,用於監聽廣告事件:

export function registerAdEvents(ad: RewardedInterstitialAd) {
  ad.adEventCallback = {
    // Called when the ad is presented on screen.
    onAdShowedFullScreenContent: () => {
      console.log('Rewarded interstitial ad showed full screen content.');
    },
    // Called when the ad is closed by the user.
    onAdDismissedFullScreenContent: () => {
      console.log('Rewarded interstitial ad dismissed full screen content.');
      ad.destroy();
    },
    // Called when presentation fails.
    onAdFailedToShowFullScreenContent: (error) => {
      console.error('Failed to show rewarded interstitial ad:', error);
      ad.destroy();
    },
    // Called when an impression is recorded.
    onAdImpression: () => {
      console.log('Rewarded interstitial ad recorded an impression.');
    },
    // Called when the user taps the ad.
    onAdClicked: () => {
      console.log('Rewarded interstitial ad was clicked.');
    },
    // Called when the ad is estimated to have earned money.
    onAdPaid: (adValue) => {
      console.log(
        `Rewarded interstitial ad paid: ${adValue.amountMicros} ${adValue.currencyCode}`,
      );
    },
  };
}

此外,當使用者關閉廣告或廣告無法顯示時,這個範例也會呼叫 destroy 方法。這個程序會釋出廣告使用的資源。

顯示廣告

如要顯示插頁式獎勵廣告,請在已載入的 RewardedInterstitialAd 執行個體上呼叫 show,並傳遞回呼來接收 Reward:

export function showRewardedInterstitialAd(
  ad: RewardedInterstitialAd,
  onRewardEarned: (reward: Reward) => void,
) {
  ad.show(onRewardEarned);
}

選用:驗證伺服器端驗證回呼

如果應用程式需要在伺服器端驗證 (SSV) 回呼中加入自訂驗證參數 (例如使用者 ID 或自訂獎勵中繼資料),請在顯示廣告前,於載入的廣告例項上設定 serverSideVerificationOptions 屬性。

您設定的值會傳遞至 SSV 回呼查詢參數:

  • userId:傳遞至 user_id 查詢參數,用於識別使用者。
  • customData:傳遞至 custom_data 查詢參數,以轉送自訂中繼資料。

以下範例在顯示廣告前,於插頁式獎勵廣告物件上設定 ServerSideVerificationOptions (customData 和 userId):

export function setServerSideVerificationRewardedInterstitial(
  ad: RewardedInterstitialAd,
) {
  ad.serverSideVerificationOptions = {
    userId: 'user_123',
    customData: 'sample_custom_data',
  };
}

查看完整範例

本節提供完整範例,說明如何將插頁式獎勵廣告整合至 React Native 原生應用程式。

以下範例將廣告整合至 React Native 元件、管理狀態中的廣告例項,並提供載入及顯示廣告的控制項:

export function RewardedInterstitialSingleLoadScreen() {
  const [ad, setAd] = useState<RewardedInterstitialAd | null>(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [status, setStatus] = useState<string>('Idle');
  const [reward, setReward] = useState<string | null>(null);

  useEffect(() => {
    return () => {
      ad?.destroy();
    };
  }, [ad]);

  const handleLoad = async () => {
    setReward(null);
    setStatus('Loading Rewarded Interstitial ad...');
    const loadedAd = await loadRewardedInterstitialAd(
      REWARDED_INTERSTITIAL_AD_UNIT_ID,
    );
    if (loadedAd) {
      registerAdEvents(loadedAd);
      const onDismiss =
        loadedAd.adEventCallback?.onAdDismissedFullScreenContent;
      loadedAd.adEventCallback = {
        ...loadedAd.adEventCallback,
        onAdDismissedFullScreenContent: () => {
          onDismiss?.();
          setStatus('Ad dismissed.');
        },
      };
      setAd((prevAd) => {
        prevAd?.destroy();
        return loadedAd;
      });
      setIsLoaded(true);
      setStatus('Rewarded Interstitial ad loaded!');
    } else {
      setStatus('Failed to load Rewarded Interstitial ad.');
    }
  };

  const handleShow = () => {
    if (ad) {
      showRewardedInterstitialAd(ad, (userReward) => {
        setReward(`${userReward.amount} ${userReward.type}`);
      });
      setIsLoaded(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Rewarded Interstitial Ad</Text>
      <Text style={styles.status}>Status: {status}</Text>
      {reward && <Text style={styles.rewardText}>Earned: {reward}</Text>}
      <View style={styles.buttonGroup}>
        <Button title="Load Ad" onPress={handleLoad} />
        <View style={styles.spacerSmall} />
        <Button title="Show Ad" onPress={handleShow} disabled={!isLoaded} />
      </View>
    </View>
  );
}

後續步驟

整合插頁式獎勵廣告後,請參閱下列主題: