技術っぽいことを書いてみるブログ

PythonとかVue.jsとか技術的なことについて書いていきます。

React NativeでGoogleAdmobのバナー広告を入れる方法

やること

  • ReactNativeでGoogleAdmobの広告を入れる
  • 広告は画面の下部にバナー広告を挿入する

ライブラリインストール

npmでreact-native-google-mobile-adsをインストールする

npm install react-native-google-mobile-ads

Google Admobにてアプリを作成する

  1. GoogleAdmobにアクセス
  2. 「アプリを追加」を押下
  3. 「新しいアプリの設定」画面で、プラットフォーム(AndroidiOS)・アプリはサポートされているアプリストアに登録されていますか?を選択する
  4. アプリ名を入力し、「アプリを追加」ボタンを押下する
  5. 「追加しました」が表示されたら、「完了」ボタンを押下する
  6. 「広告ユニットを追加」ボタンを押下する
  7. 「バナー」を選択する
  8. 広告ユニット名を適当に入力し、「パートナーでの入札」はチェックせずに、「広告ユニットの作成」ボタンを押下
  9. 「広告ユニットを作成しました」が表示されるので、アプリIDと広告ユニットIDをひかえておく。

バナー広告用のコンポーネントの作成

MyAdmob.tsx

import {Platform, View} from 'react-native';
import mobileAds, {
  BannerAd,
  BannerAdSize,
  TestIds,
} from 'react-native-google-mobile-ads';

type Props = {
  size: BannerAdSize;
};

const MyAdmob: React.FC<Props> = props => {
  const isDebug = false;  // テスト時はtrueにする

  mobileAds()
    .setRequestConfiguration({
      // Indicates that you want your content treated as child-directed for purposes of COPPA.
      tagForChildDirectedTreatment: true,
    })
    .then(() => {
      // Request config successfully set!
      console.log('Request config successfully set!');
    });

  // 実際に広告配信する際のID
  // 広告ユニット(バナー)を作成した際に表示されたものを設定する
  const adUnitID = Platform.select({
    ios: 'ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy',
    android: 'ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy',
  });

  const getUnitId = () => {
    return isDebug ? TestIds.BANNER : adUnitID ?? TestIds.BANNER;
  };

  return <BannerAd {...props} unitId={getUnitId()} />;
};

export default MyAdmob;

App.tsxに広告のコンポーネントの表示を組み込む

  return (
    <>
      ・・・
      <MyAdmob size={BannerAdSize.ANCHORED_ADAPTIVE_BANNER} />
    </>
  );

アプリケーションIDをapp.jsonに設定する

  • app.json に以下を設定する
{
  "name": "",
  "displayName": "",
  "react-native-google-mobile-ads": {
    "android_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx",
    "ios_app_id": "ca-app-pub-xxxxxxxx~xxxxxxxx"
  }
}

シミュレーターを実行して確認

はい、表示されています!

リリース版のときは、MyAdmobコンポーネントのisDebug=falseにするのを忘れずに・・・