react-native 앱에 광고 삽입[3]
Test 광고
firebase, admob 세팅을 모두 마쳤으니, react-native 코드를 수정하여 test 광고를 띄워 보도록 하자
1. react-native-firebase 라이브러리 설치
yarn add @react-native-firebase/app yarn add @react-native-firebase/admob
먼저 react-native 프로젝트 루트로 가서 위 라이브러리를 설치 한다. 이상태에서 npx react-native run-android 로 실행 시 아래와 같은 에러가 출력됐다.
The number of method references in a .dex file cannot exceed 64K.

Android 프로젝트를 빌드 하면 서 생기는 바이트 코드가 .dex 파일에 써지게 되는데 이 .dex 파일이 64K로 제한되어 있다는 내용이라고 구글신이 알려줬다. 해결법은 아래 내용을 android\app\build.gradle에 아래 내용을 추가해 주면 된다.
android {
...
defaultConfig {
...
multiDexEnabled true
}
}
그리고 아래처럼 clean 한번 해주고 다시 실행 시키면 정상 동작 한다.
cd android .\gradlew clean .. npx react-native run-android
2. 코드
아래와 같은 Component를 만든다. 필자는 utils 폴더 및에 Ads.js 파일을 만들고 그 안에 광고를 출력하는 함수를 만들어 줬다.
여기서 __DEV__ 변수는 해당앱이 Development 모드인지 Production 모드인지를 체크 해준다. 즉 build를 하기 이전에 Android/iOS시뮬레이터에 올려서 테스트 하는 경우는 해당 값이 True 이다.
import React from 'react';
import { BannerAd, BannerAdSize, TestIds, AdEventType } from '@react-native-firebase/admob';
//const adBannerUnitId = __DEV__ ? TestIds.BANNER : 'ca-app-pub-xxxxxxxxxxxxx/yyyyyyyyyyyyyy'; // 광고 ID 입력
export const BottomBannerAds = () => (
<BannerAd
unitId={adBannerUnitId}
size={BannerAdSize.FULL_BANNER}
requestOptions={{
requestNonPersonalizedAdsOnly: true,
}}
onAdLoaded={() => {
console.log('Advert loaded');
}}
onAdFailedToLoad={(error) => {
console.error('Advert failed to load: ', error);
}}
/>
)
원하는 스크린에서 위 함수를 render 부분에서 호출해 주면 된다. 아래 코드는 Settings 라는 스크린에서 광고를 출력하는 경우이다.
import React from 'react';
import { View,
StyleSheet,
Text,
} from 'react-native';
import {BottomBannerAds} from '../utils/Ads'
class Settings extends React.Component {
render() {
return (
<View style={styles.container}>
<Text> Hello Settings </Text>
{
BottomBannerAds()
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
}
});
export default Settings
그러면 아래처럼 Nice job ~ 하면서 광고가 출력되면 정상이다.

다른 광고를 만드는 방법은 https://rnfirebase.io/admob/displaying-ads 공식 사이트를 참조하면 된다.



