본문 바로가기
개발로그/ReactNative

2023. ver2. admob IOS 앱 첫 연동하기 예제 CRNA app (Expo Dev Client and EAS CLI)

by 그리너리디밸로퍼 2023. 2. 6.

 

 

    2023.02.06 - [개발로그/ReactNative] - 2023. Ver1 . admob 첫 연동하기 정리 CRNA app (with IOS)

     

     

    구글 애드몹에 가입하고 앱을 생성하는 단계까지는  위 포스팅의 내용과 동일합니다. 유투브에 다른 방법으로 연동하는 것이 있어서 테스트해보았습니다.

     

    Setup/Installation - Expo Dev Client and EAS CLI -  

    Setup

    cd expo-rn-demo-with-ads
    expo install expo-dev-client
    expo install react-native-google-mobile-ads
    
    npx pod-install ios

    Add to app.json 

    ios_app_id 는 자신이 발급 받은 것으로 해야합니다. 구글애드몹 사이트에서 앱정보->앱설정 화면에서 앱ID 를 확인할 수 있습니다.

    {
     "expo": {
    	(중략)
     },  
     "react-native-google-mobile-ads": {
        "android_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx",
        "ios_app_id": "ca-app-pub-6694869363005240~6830759351"
     }
    }

     eas-cli 를 설치한 적이 없다면 아래와 같이 설치합니다.

    npm install -g eas-cli

    각각의 명령어를 실행하여 eas 에 login하고 eas.json 파일을 생성합니다. 

    (*제 경우에는 빌드 전에 package.lock.json 파일이 있으면 빌드실패했습니다. 그래서 *.lock.json 파일은 모두 삭제하였습니다.)

    // login
    eas login
    
    // 빌드를 위한 eas.json 파일을 생성합니다.
    eas build:configure

     Add eas.json

      
      
      "build": {
        "development": {
          "developmentClient": true,
          "distribution": "internal",      
          "ios": {
            "simulator": true,
            "buildConfiguration": "Debug"
          }

    빌드 테스트

    npx eas-cli build --profile development

    첫 빌드 테스트만 위 명령어로 하고, 이후에는 npm run ios 또는 npx react-native run-ios 로 코드 수정후 테스트해도 무관합니다.

     

    빌드에 성공했다면, 배너를 넣어봅니다. 전체 코드는 가장 하단에 첨부해두었습니다.

    Banner Ads -

    import {
      AdEventType,
      BannerAdSize,
      RewardedAdEventType,
      RewardedInterstitialAd,
      InterstitialAd,
      BannerAd,
      TestIds,
    } from "react-native-google-mobile-ads";

    unitId(광고ID)는 TestIds 로 하였고, 배너의 크기와 사용자맞춤형 광고만 표시하도록 설정했습니다.

    <SafeAreaView style={styles.container}> 
          <BannerAd
            unitId={TestIds.BANNER}
            size={BannerAdSize.LARGE_BANNER}
            requestOptions={{ requestNonPersonalizedAdsOnly: true }}
          />
    </SafeAreaView>

     

    Interstitial Ads -

    좌측 버튼을 클릭하면 우측 광고가 팝업된다.

     

    import {
      AdEventType,
      BannerAdSize,
      RewardedAdEventType,
      RewardedInterstitialAd,
      InterstitialAd,
      BannerAd,
      TestIds,
    } from "react-native-google-mobile-ads";
    
    const interstitial = InterstitialAd.createForAdRequest(TestIds.INTERSTITIAL, {
      requestNonPersonalizedAdsOnly: true,
    });

     

    // export default function App() { 내부

     

      const [InterstitialLoaded, setInterstitialLoaded] = useState(false);
     
      const loadingIntersitital = () => {
        const unsubscribeLoaded = interstitial.addAdEventListener(
          AdEventType.LOADED,
          () => {
            setInterstitialLoaded(true);
          }
        );
        const unsubscribeClosed = interstitial.addAdEventListener(
          AdEventType.CLOSED,
          () => {
            setInterstitialLoaded(false);
            interstitial.load();
          }
        );
    
        interstitial.load();
        return () => {
          unsubscribeClosed();
          unsubscribeLoaded();
        };
      };
      
    useEffect(() => {
        const unsubscribeInterstitialEvents = loadingIntersitital(); 
        return () => unsubscribeInterstitialEvents();
      }, []);

    // components

    <SafeAreaView style={styles.container}>
          {InterstitialLoaded ? (
            <Button
              title="Show Interstitial"
              onPress={() => interstitial.show()}
            ></Button>
          ) : (
            <Text>Loading Interstitial</Text>
          )}
           
          <BannerAd
            unitId={TestIds.BANNER}
            size={BannerAdSize.BANNER}
            requestOptions={{ requestNonPersonalizedAdsOnly: true }}
          />
    </SafeAreaView>

     

    Rewarded Interstitial Ads -

    import {
      AdEventType,
      BannerAdSize,
      RewardedAdEventType,
      RewardedInterstitialAd,
      InterstitialAd,
      BannerAd,
      TestIds,
    } from "react-native-google-mobile-ads";

    // loadingRewardedIntersitital () and useEffect()

     const [RewardedInterstitialLoaded, setRewardedInterstitialLoaded] =
        useState(false);
    
    const loadingRewardedIntersitital = () => {
        const unsubscribeLoaded = rewaredeInterstitial.addAdEventListener(
          RewardedAdEventType.LOADED,
          () => {
            setRewardedInterstitialLoaded(true);
          }
        );
        const unsubscribeEarned = rewaredeInterstitial.addAdEventListener(
          RewardedAdEventType.EARNED_REWARD,
          (reward) => {
            console.log(`User earned reward of ${reward.amount} ${reward.type}`);
          }
        );
        const unsubscribeClosed = rewaredeInterstitial.addAdEventListener(
          // ** EventType 이 다름.
          AdEventType.CLOSED,
          () => {
            setRewardedInterstitialLoaded(false);
            rewaredeInterstitial.load();
          }
        );
        rewaredeInterstitial.load();
        return () => {
          unsubscribeLoaded();
          unsubscribeClosed();
          unsubscribeEarned();
        };
      };
      useEffect(() => {
        const unsubscribeInterstitialEvents = loadingIntersitital();
        const unsubscribeRewardInterstitialEvents = loadingRewardedIntersitital();
        return () => {
          unsubscribeInterstitialEvents();
          unsubscribeRewardInterstitialEvents();
        };
      }, []);

    // components

        <SafeAreaView style={styles.container}>
     
          {RewardedInterstitialLoaded ? (
            <Button
              title="Show RewardedInterstitial"
              onPress={() => rewaredeInterstitial.show()}
            ></Button>
          ) : (
            <Text>Loading Rewarded Interstitial</Text>
          )}
     
        </SafeAreaView>

    Why you have to use Expo Dev Client and not Expo Go - 

    위 예제는 테스트를 위한 devlopment 빌드이며, Expo go 를 사용한다면 Admob을 볼 수 없습니다. 왜냐하면 native modules와 link e되지 않았기 때문입니다. 

    Admob이 어떻게 동작하는지 이해하기 위한 간단한 예제로 활용하시면 좋을 것 같습니다.

     

     

    새로운 expo 버전을 위한 Admob 관련 문서는 

    https://docs.page/invertase/react-native-google-mobile-ads

     

     


    작성된 App.js 첨부

    App.js
    0.00MB

     

     

    728x90

    댓글