Межстраничная реклама

Межстраничная реклама (Interstitial) — полноэкранный формат рекламы, встраиваемый в контент приложения во время естественных пауз, таких как переход между уровнями игры или окончание выполнения целевого действия.

Сущность

Описание

onAdFailedToShow

При получении ошибки в onAdFailedToShow() не пытайтесь загружать новое объявление снова из этого же метода.

adUnitId

Используйте:

  • development mode — для работы с демоблоками;

  • production mode — для работы с R-M-XXXXXX-Y (уточните реальный ID в интерфейсе Рекламной сети Яндекса). R-M-XXXXXX-Y — это вид рабочего рекламного ID, по которому будут приходить разные креативы.

Пример создания межстраничной рекламы

import React, { useState } from 'react';
import { Alert, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { AdRequestConfiguration, InterstitialAd, InterstitialAdLoader } from 'yandex-mobile-ads';

const INTERSTITIAL_AD_UNIT_ID = 'demo-interstitial-yandex'; // Замените на ваш ID

export default function InterstitialView() {
  const [isLoaded, setIsLoaded] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [interstitialAd, setInterstitialAd] = useState<InterstitialAd | null>(null);

  const loadAd = async () => {
    try {
      setIsLoading(true);

      // 1. Создаем loader
      const loader = await InterstitialAdLoader.create();

      // 2. Создаем конфигурацию запроса
      const adRequestConfiguration = new AdRequestConfiguration({
        adUnitId: INTERSTITIAL_AD_UNIT_ID,
      });

      // 3. Загружаем рекламу
      const ad = await loader.loadAd(adRequestConfiguration);

      console.log('Interstitial ad loaded');

      // 4. Настраиваем обработчики событий
      ad.onAdShown = () => {
        console.log('Interstitial ad shown');
      };

      ad.onAdDismissed = () => {
        console.log('Interstitial ad dismissed');
        setIsLoaded(false);
        setInterstitialAd(null);
      };

      ad.onAdClicked = () => {
        console.log('Interstitial ad clicked');
      };

      ad.onAdImpression = (impressionData) => {
        console.log('Interstitial impression:', impressionData);
      };

      ad.onAdFailedToShow = (error) => {
        console.error('Interstitial failed to show:', error);
        Alert.alert('Ad Failed to Show', JSON.stringify(error));
        setIsLoaded(false);
      };

      setInterstitialAd(ad);
      setIsLoaded(true);
      setIsLoading(false);

    } catch (error) {
      console.error('Failed to load interstitial ad:', error);
      Alert.alert('Ad Failed to Load', JSON.stringify(error));
      setIsLoading(false);
      setIsLoaded(false);
    }
  };

  const showAd = () => {
    if (interstitialAd && isLoaded) {
      interstitialAd.show();
    } else {
      Alert.alert('Ad not ready', 'Please load the ad first');
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Interstitial Ad</Text>

      <TouchableOpacity
        style={[styles.button, isLoading && styles.buttonDisabled]}
        onPress={loadAd}
        disabled={isLoading}
      >
        <Text style={styles.buttonText}>
          {isLoading ? 'Loading...' : 'Load Ad'}
        </Text>
      </TouchableOpacity>

      <TouchableOpacity
        style={[styles.button, styles.showButton, !isLoaded && styles.buttonDisabled]}
        onPress={showAd}
        disabled={!isLoaded}
      >
        <Text style={styles.buttonText}>Show Ad</Text>
      </TouchableOpacity>

      <Text style={styles.status}>
        {isLoaded ? '✅ Ad Ready' : '❌ Ad Not Loaded'}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 40,
  },
  button: {
    backgroundColor: '#007AFF',
    paddingVertical: 15,
    paddingHorizontal: 40,
    borderRadius: 10,
    marginVertical: 10,
    width: '80%',
    alignItems: 'center',
  },
  showButton: {
    backgroundColor: '#34C759',
  },
  buttonDisabled: {
    backgroundColor: '#ccc',
  },
  buttonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  status: {
    marginTop: 30,
    fontSize: 16,
    color: '#666',
  },
});

Проверка интеграции

Проверить работу рекламных форматов можно на нашем демо-проекте.