Charger une seule annonce interstitielle

Les annonces interstitielles sont des annonces en plein écran qui s'affichent à des points de transition dans votre application, par exemple entre deux écrans ou pendant la pause entre deux niveaux de jeu. Vos utilisateurs peuvent appuyer sur l'annonce pour accéder à la destination, ou la fermer et revenir à l'application. Pour en savoir plus, consultez les consignes concernant les annonces interstitielles et une étude de cas.

Ce guide vous explique comment intégrer des annonces interstitielles dans une application React Native.

Prérequis

Android

ca-app-pub-3940256099942544/1033173712

iOS

ca-app-pub-3940256099942544/4411468910

Charger une annonce

Pour charger une annonce interstitielle, appelez la méthode load sur la classe InterstitialAd.

L'exemple suivant charge une annonce interstitielle en cas de réussite et consigne une erreur en cas d'échec :

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

Écouter les événements d'annonce

Avant de diffuser l'annonce, définissez l'écouteur adEventCallback sur l'instance InterstitialAd chargée. Cet écouteur reçoit des rappels pour les événements du cycle de vie de l'annonce, par exemple lorsque l'annonce s'affiche à l'écran ou qu'un utilisateur appuie dessus. Pour connaître les rappels disponibles, consultez AdEventCallback.

L'exemple suivant définit des rappels pour écouter les événements d'annonce :

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

Cet exemple appelle également la méthode destroy lorsqu'un utilisateur ferme l'annonce ou lorsque l'annonce ne s'affiche pas. Ce processus libère les ressources utilisées par l'annonce.

Diffuser l'annonce

Pour afficher une annonce interstitielle, appelez la méthode show sur l'instance InterstitialAd chargée.

L'exemple suivant montre une annonce interstitielle :

export function showInterstitialAd(ad: InterstitialAd) {
  ad.show();
}

Voir l'exemple complet

Cette section présente un exemple complet d'intégration d'une annonce interstitielle dans une application React Native.

L'exemple suivant intègre l'annonce dans un composant React Native, gère l'instance d'annonce dans l'état et fournit des commandes pour charger et afficher l'annonce :

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

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

  const handleLoad = async () => {
    setStatus('Loading Interstitial ad...');
    const loadedAd = await loadInterstitialAd(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('Interstitial ad loaded!');
    } else {
      setStatus('Failed to load Interstitial ad.');
    }
  };

  const handleShow = () => {
    if (ad) {
      showInterstitialAd(ad);
      setIsLoaded(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Interstitial Ad</Text>
      <Text style={styles.status}>Status: {status}</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>
  );
}

Étapes suivantes

Après avoir intégré des annonces interstitielles, explorez les sujets suivants :