배너 광고 설정

배너 광고는 기기 화면의 상단이나 하단과 같이 앱 레이아웃의 고정된 위치에 게재됩니다. 이러한 광고는 사용자가 앱과 상호작용하는 동안 화면에 표시되며, 설정한 시간이 지나면 새로고침됩니다. 적응형 앵커 배너는 사용자가 지정한 광고 너비를 사용하여 각 기기에 맞게 광고 크기를 최적화합니다.

이 페이지에서는 적응형 앵커 배너 광고를 React Native 네이티브 앱에 통합하는 방법을 설명합니다.

기본 요건

계속하기 전에 다음을 수행하세요.

Android

ca-app-pub-3940256099942544/9214589741

iOS

ca-app-pub-3940256099942544/2435281174

광고 크기 가져오기

적응형 앵커 배너 광고를 요청하려면 사용 가능한 광고 컨테이너 너비(밀도 독립형 픽셀(dp))를 사용하여 AdSize.getLargeAnchoredAdaptiveBannerAdSize 메서드를 호출합니다. 이 메서드는 AdSize 객체로 확인되는 프로미스를 반환합니다.

다음 예에서는 적응형 앵커 배너 광고의 광고 크기를 가져와 반환합니다.

export async function getAdaptiveAdSize(width: number): Promise<AdSize> {
  const adSize = await AdSize.getLargeAnchoredAdaptiveBannerAdSize(width);
  return adSize;
}

광고 로드하기

AdSize 객체를 가져온 후 광고 단위 ID와 광고 크기를 사용하여 BannerAd 클래스에서 load 메서드를 호출합니다.

다음 예에서는 광고 크기 및 광고 단위 ID를 사용하여 적응형 앵커 배너 광고를 로드하고, 성공 시 로드된 BannerAd 인스턴스를 수신하고, 실패 시 오류를 로깅합니다.

export function loadBannerAd(
  adUnitId: string,
  adSize: AdSize,
  callback?: BannerAdLoadCallback,
): void {
  BannerAd.load(
    {adUnitId, adSize},
    {
      // Called when an ad has finished loading.
      onAdLoaded: (ad) => {
        console.log('Banner ad loaded successfully.');
        callback?.onAdLoaded?.(ad);
      },
      // Called when an ad request fails.
      onAdFailedToLoad: (error: LoadAdError) => {
        console.error('Failed to load banner ad:', error.message);
        callback?.onAdFailedToLoad?.(error);
      },
    },
  );
}

광고 새로고침

광고 단위가 새로고침되도록 설정한 경우 광고 로드에 실패했을 때 다른 광고를 요청하지 않아도 됩니다. Google Mobile Ads SDK for React Native는 AdMob UI에 지정된 새로고침 빈도를 따릅니다. 새로고침을 사용 설정하지 않았다면 새로 요청하세요. 배너 광고에 자동 새로고침 사용에서 새로고침 빈도 설정과 같은 광고 단위 새로고침에 대한 자세한 내용을 참고하세요.

배너 광고 표시하기

로드된 BannerAd 인스턴스를 표시하려면 광고 인스턴스를 뷰 계층 구조에 있는 BannerAdView 구성요소의 ad 속성에 전달합니다.

다음 예에서는 광고를 표시하고 구성요소가 마운트 해제될 때 광고를 소멸시킵니다.

export function BannerAdViewComponent({ad}: {ad: BannerAd}): React.JSX.Element {
  useEffect(() => {
    // Destroy native resources when the component unmounts.
    return () => {
      ad.destroy();
    };
  }, [ad]);

  return <BannerAdView ad={ad} />;
}

이 예에서는 구성요소가 마운트 해제되거나 광고 인스턴스가 교체될 때 destroy 메서드를 호출합니다. 이 프로세스는 광고에서 사용하는 메모리와 리소스를 확보합니다.

광고 이벤트 수신 대기

광고 노출 및 클릭과 같은 광고 이벤트를 수신 대기하려면 BannerAdView 구성요소에서 콜백을 설정하세요. 모든 콜백은 BannerAdViewProps를 참조하세요.

다음 예에서는 배너 광고 이벤트를 수신 대기하도록 콜백을 설정합니다.

export function BannerEventsExample({ad}: {ad: BannerAd}): React.JSX.Element {
  return (
    <BannerAdView
      ad={ad}
      // Called when an impression is recorded for an ad.
      onAdImpression={() => {
        console.log('Banner ad recorded an impression.');
      }}
      // Called when a click is recorded for an ad.
      onAdClicked={() => {
        console.log('Banner ad clicked.');
      }}
      // Called when the ad opens an in-app overlay or landing page.
      onAdShowedFullScreenContent={() => {
        console.log('Banner ad opened overlay content.');
      }}
      // Called when the user dismisses the ad overlay.
      onAdDismissedFullScreenContent={() => {
        console.log('Banner ad overlay dismissed.');
      }}
      // Called when the ad is estimated to have earned money.
      onAdPaid={(adValue) => {
        console.log(
          `Banner ad paid: ${adValue.amountMicros} ${adValue.currencyCode}`,
        );
      }}
      // Called when the ad automatically refreshes.
      onAdRefreshed={() => {
        console.log('Banner ad refreshed.');
      }}
      // Called when the ad fails to automatically refresh.
      onAdFailedToRefresh={(error) => {
        console.error('Banner ad failed to refresh:', error.message);
      }}
    />
  );
}

이 예에서는 광고 닫기, 노출, 클릭, 전체 화면 표시, 예상 광고 수익, 새로고침 성공 및 실패와 같은 광고 이벤트를 수신 대기합니다.

전체 예시 보기

이 섹션에서는 배너 광고를 React Native 구성요소에 통합하는 전체 예를 다룹니다.

다음 예에서는 배너 광고를 React Native 구성요소에 통합하고 상태에서 광고 인스턴스를 관리합니다.

export function BannerScreen() {
  const {width} = useWindowDimensions();
  const insets = useSafeAreaInsets();
  const [ad, setAd] = useState<BannerAd | null>(null);
  const [status, setStatus] = useState('Idle');

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

  const handleLoadAd = async () => {
    setStatus('Loading adaptive banner ad...');
    try {
      const adaptiveSize = await getAdaptiveAdSize(width);
      loadBannerAd(BANNER_AD_UNIT_ID, adaptiveSize, {
        onAdLoaded: (loadedAd) => {
          setAd(loadedAd);
          setStatus('Banner ad loaded successfully.');
        },
        onAdFailedToLoad: (error: LoadAdError) => {
          setStatus(`Failed to load banner ad: ${error.message}`);
        },
      });
    } catch (error) {
      setStatus(`Failed to get adaptive ad size: ${error}`);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Anchored Adaptive Banner Ad</Text>
      <Text style={styles.status}>Status: {status}</Text>
      <View style={styles.buttonGroup}>
        <Button title="Load Banner Ad" onPress={handleLoadAd} />
      </View>
      {ad ? (
        <View style={[styles.bannerContainer, {bottom: insets.bottom}]}>
          <BannerAdView
            ad={ad}
            onAdImpression={() => setStatus('Banner ad recorded impression.')}
            onAdClicked={() => setStatus('Banner ad clicked.')}
            onAdShowedFullScreenContent={() =>
              setStatus('Banner ad showed overlay content.')
            }
            onAdDismissedFullScreenContent={() =>
              setStatus('Banner ad overlay dismissed.')
            }
          />
        </View>
      ) : null}
    </View>
  );
}

BANNER_AD_UNIT_ID를 광고 단위 ID로 바꿉니다.

다음 단계

배너 광고를 통합한 후 다음 주제를 살펴보세요.