טעינה של מודעת מעברון יחידה

מודעות מעברון הן מודעות במסך מלא שמופיעות בנקודות מעבר באפליקציה, למשל בין מסכים או במהלך ההשהיה בין שלבים במשחק. המשתמשים יכולים ללחוץ על המודעה כדי לעבור ליעד, או לסגור את המודעה ולחזור לאפליקציה. פרטים נוספים זמינים בהנחיות למודעות מעברון ובמקרה לדוגמה.

במדריך הזה מוסבר איך לשלב מודעות מעברון באפליקציית React Native.

דרישות מוקדמות

Android

ca-app-pub-3940256099942544/1033173712

iOS

ca-app-pub-3940256099942544/4411468910

טעינת מודעה

כדי לטעון מודעת מעברון, צריך להפעיל את השיטה load במחלקה InterstitialAd.

בדוגמה הבאה, אם המודעה נטענת בהצלחה, הפונקציה טוענת מודעת מעברון, ואם לא, היא מתעדת שגיאה:

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;
  }
}

האזנה לאירועים של מודעות

לפני שמציגים את המודעה, מגדירים את המאזין adEventCallback במופע InterstitialAd שנטען. המאזין הזה מקבל קריאות חוזרות (callbacks) לאירועים במחזור החיים של המודעה, כמו הצגת המודעה במסך או לחיצה של המשתמש על המודעה. אפשר לראות את הקריאות החוזרות הזמינות במאמר AdEventCallback.

בדוגמה הבאה מוגדרות קריאות חוזרות (callback) כדי להאזין לאירועי מודעות:

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}`,
      );
    },
  };
}

בדוגמה הזו, המערכת קוראת ל-method‏ destroy גם כשהמשתמש סוגר את המודעה או כשהמודעה לא מוצגת. התהליך הזה משחרר את המשאבים שבהם המודעה השתמשה.

הצגת המודעה

כדי להציג מודעת מעברון, צריך להפעיל את ה-method‏ show במופע InterstitialAd שנטען.

הדוגמה הבאה מציגה מודעת מעברון:

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

לצפייה בדוגמה המלאה

בקטע הזה מופיעה דוגמה מלאה לשילוב של מודעת מעברון באפליקציית נייטיב של React Native.

בדוגמה הבאה, המודעה משולבת ברכיב React Native, מופע המודעה מנוהל במצב, ויש אמצעי בקרה לטעינה ולהצגה של המודעה:

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>
  );
}

השלבים הבאים

אחרי שמשלבים מודעות מעברון, כדאי לעיין בנושאים הבאים: