Adding AdMob In Ionic 2

Advertisement:

Today lets implement AdMob’s Banner Ads, Interstitial Ads and Rewarded Interstitial or Rewarded Video Ads in our Ionic 2 application.

We’ve installed a blank template for this tutorial

ionic start technotip blank --v2

We create a Ionic 2 project by name ‘technotip’ with blank template.

Related Read: Ionic 2 Starter Templates

Implementing AdMob Ads In Ionic 2



YouTube Link: http://www.youtube.com/watch?v=Dj2n_25hcko [Watch the Video In Full Screen.]



Package version information:

C:\ionic2\technotip>ionic info
 
Your system information:
 
Cordova CLI: 6.1.1
Ionic Framework Version: 2.0.0-rc.4
Ionic CLI Version: 2.1.17
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.47
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.7.0
Xcode version: Not installed

Steps To Follow
Step 1: Install AdMobPro plugin
Step 2: Add Platform
Step 3: Implement AdMob into your Ionic 2 project
Step 4: Install your Ionic 2 app to your device to test AdMob ads.

ionic2-admob

Note: Make sure to navigate to your ionic 2 project folder before executing any commands.
Example: Our Ionic 2 project name is ‘technotip’, which is inside a folder called ionic2. So I execute all commands once I get inside

C:\>cd ionic2
C:\ionic2>cd technotip
C:\ionic2\technotip>ionic serve -l -c

Step 1: Install AdMobPro plugin

ionic plugin add cordova-plugin-admobpro

This installs AdMobPro plugin to our Ionic 2 project.

Step 2: Add Platform

ionic platform add android
 
OR
 
ionic platform add ios

If you are developing ios app, then add ios platform(for this, you must be on a Mac). If you’re developing android app, then add android as platform. If you face any difficulty with this step or in installing Ionic framework, please refer to Ionic 2 Starter Templates video tutorial.

Step 3: Implement AdMob into your Ionic 2 project
1. Banner Ads

To show banner ads in all the views of our app, we need to code it inside src/app/app.component.ts

import { AdMob } from 'ionic-native';

Import AdMob Class.

      let options = {
        adId: 'ca-app-pub-5732334124058455/7973166445',
        adSize: 'SMART_BANNER',
        isTesting: false
      };
 
      AdMob.createBanner(options).then(() => {
        AdMob.showBanner(8);
      });

Pass configuration information to createBanner method which returns a promise. After configuring the Banner information call showBanner method and pass the ad position number.

adId – must be AdMob ads banner id.
adSize – Takes following values SMART_BANNER, BANNER, MEDIUM_RECTANGLE, FULL_BANNER, LEADERBOARD, SKYSCRAPER, or CUSTOM. By default it takes the value ‘SMART_BANNER’.
isTesting – Give it true in development and false to show real ads in production.

showBanner method takes a number as parameter.
0 – NO_CHANGE;
1 – TOP_LEFT;
2 – TOP_CENTER;
3 – TOP_RIGHT;
4 – LEFT;
5 – CENTER;
6 – RIGHT;
7 – BOTTOM_LEFT;
8 – BOTTOM_CENTER;
9 – BOTTOM_RIGHT;
10 – POS_XY;

Important Note: If you’re placing any Ionic Native Plugins code inside constructor, then make sure to wrap it around Platform.ready() method orelse it’ll start throwing errors. Since code inside constructor executes as soon as the class is instantiated, the external libraries might not yet have loaded, which causes the code inside constructor to break. If we wrap the code inside platform ready, the code executes only after the device platform is ready.

Full Source Code: src/app/app.component.ts

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen, AdMob } from 'ionic-native';
 
import { HomePage } from '../pages/home/home';
 
 
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage = HomePage;
 
  constructor(platform: Platform) {
    platform.ready().then(() => {
 
      let options = {
        adId: 'ca-app-pub-5732334124058455/7973166445',
        adSize: 'SMART_BANNER',
        isTesting: false
      };
 
      AdMob.createBanner(options).then(() => {
        AdMob.showBanner(8);
      });
 
    });
  }
}

2. Interstitial Ad
We shall invoke an interstitial ad once the user clicks on a button – for demo purpose.

src/pages/home/home.html

  < p>
    < button ion-button (click)="loadAd();">Show Ad< /button>
  < /p>

We’ve added the button to our UI. Once the user clicks on the button, we invoke loadAd() method.

src/pages/home/home.ts

  loadAd(){
   let options = {
    adId: 'ca-app-pub-5732334124058455/3403366048',
    isTesting: false
   };
    AdMob.prepareInterstitial(options)
         .then(() => {
           AdMob.showInterstitial();
         });
  };

we pass interstitial ad units adId to prepareInterstitial() method and then once the promise is returned we invoke showInterstitial() method. We can even pass isTesting option with true or false Boolean value.

Full Source Code: src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
 
import { AdMob } from 'ionic-native';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 
  constructor(public navCtrl: NavController) {
 
  }
  loadAd(){
   let options = {
    adId: 'ca-app-pub-5732334124058455/3403366048',
    isTesting: false
   };
    AdMob.prepareInterstitial(options)
         .then(() => {
           AdMob.showInterstitial();
         });
  };
}

Make sure to import ‘AdMob’ at the top of home component.

3. Rewarded Interstitial or Rewarded Video Ad

import { Component } from '@angular/core';
 
import { NavController } from 'ionic-angular';
 
import { AdMob } from 'ionic-native';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 
  constructor(public navCtrl: NavController) {
 
  }
  loadAd(){
   let options = {
    adId: 'ca-app-pub-5732334124058455/7216350441',
    isTesting: false
   };
    AdMob.prepareRewardVideoAd(options)
         .then(() => {
           AdMob.showRewardVideoAd();
         });
  };
}

Pass rewarded interstitial or rewarded video ads adId to prepareRewardVideoAd() method and then invoke showRewardVideoAd() method.

Step 4: Install your Ionic 2 app to your device to test AdMob ads

ionic run android -l -c

If you include -l and -c options while installing the project to your device, then you’ll get the live reload and log facility. But you need to be connected to the same network as your terminal where you’re ionic 2 project is running. For Example: Same WiFi for your device as well as your terminal. If your computer is using WiFi and your mobile is using service providers Data connection then this won’t work – in such case use ionic run android command, and you won’t get live reload and log information in the terminal.

Troubleshoot
If you’re getting following errors:
cordova_not_found

OR

int org.json.JSONObject.length() on null

Check these 3 things:
1. You’ve installed proper plugin. Check using ionic plugin list command.
2. You’ve imported the plugin wherever you’re using its service.
3. You’ve wrapped the plugins service code inside Platform.ready() method.

If all above 3 conditions are set right, then try this:

Remove platform and add it once again.

ionic platform rm android
ionic platform add android

Now install the project ionic run android -l -c to your device and check.

Important Note: Most Ionic Native plugins work only on the real devices, so do not try to test it using browsers.

Advertisements

11 thoughts on “Adding AdMob In Ionic 2”

  1. I want to add Vungle to my Ionic 2 project to show video rewards but I get this error:

    Cannot find an ad network adapter with the name(s): com.vungle.mediation.VungleAdapter. Remember to link all required ad network adapters and SDKs, and set -ObjC in the ‘Other Linker Flags’ setting of your build target.
    AdMob, onAdFailLoad, {‘adNetwork’:’AdMob’,’adType’:’rewardvideo’,’adEvent’:’onAdFailLoad’,’error’:9,’reason’:’No ad returned from any ad server.’}

    I have configured mediation with Vungle correctly. I get the same error with Adcolony.

    1. @Fer Medina, It’s something that needs to be fixed at the end of AdMob. Maybe fault with their mediation adapters. You can mail their support team and they’ll rectify it. On other note: have you entered proper/correct API keys and ad unit ids of Vungl and Adcolony inside AdMob Mediation?

  2. Argument of type ‘{ adId: string; adSize: string; isTesting: boolean; }’ is not assignable to parameter of
    type ‘string | AdMobOptions’. Type ‘{ adId: string; adSize: string; isTesting: boolean; }’ is not assignable
    to type ‘AdMobOptions’. Types of property ‘adSize’ are incompatible. Type ‘string’ is not assignable to type
    ‘AdMobAdSize’.

    L24: AdMob.createBanner(options).then(() => {
    L25: AdMob.showBanner(8);

      1. @satish
        First of all thank you so much for ur valuable reply. I m sharing here all my codes.

        export class MyApp {
        rootPage = TabsPage;
        options=[];
        adId;
        adSize;
        isTesting;
        interstitialReady;
        constructor(platform: Platform) {
        platform.ready().then(() => {
        StatusBar.styleDefault();
        Splashscreen.hide();
        let options = {
        adId: ‘ca-app-pub-abcdefghijkale’,
        isTesting: true
        };

        AdMob.createBanner(options).then(() => {
        AdMob.showBanner(8);
        });
        AdMob.onAdDismiss().subscribe(() => {
        interstitialReady = false;
        AdMob.prepareInterstitial({
        adId: options.adId,
        autoShow: false
        });
        });

        // Okay, so the platform is ready and our plugins are available.
        // Here you can do any higher level native things you might need.

        });
        }
        }

        from above code it was working absolutely ok. banner was showing, interstitial ads r showing only once before adding the below code. But I wanted to show this for every level of my apps. So that after dismiss the interstitial ads I wanted to prepare interstitial ads. For this I added below code which makes the code wrong and the added code is

        AdMob.onAdDismiss().subscribe(() => {
        interstitialReady = false;
        AdMob.prepareInterstitial({
        adId: options.adId,
        autoShow: false
        });
        });

        for adding this above code it shows below error

        Cannot find name ‘interstitialReady’.

        L46: AdMob.onAdDismiss().subscribe(() => {
        L47: interstitialReady = false;
        L48: AdMob.prepareInterstitial({

        but if I again remove the code, works fine. Can u plz help me to solve. Thnx

  3. Why Interstitial only once loading ? I want that if I close the add and click button again, it will load new Interstitial, How its possible

    1. @ashraful haque, It shows ads most of the times. But then it has some limits that you can set in your AdMob account or if the ad request is too frequent, AdMob itself limits the serving of ads for better user experience.

      In order to limit such behavior, you can add mediation ad networks to your ads, that way when AdMob doesn’t serve ads, it can use mediation networks ads instead and you could get to see ads most of the times.

      But still it doesn’t create good user experience, so better be careful with it. And 100% fill rate is not guarantied with any Mobile AdNetworks.

      1. thnx, ad request will not be too frequent. But I need to show interstitial adds more than one time. So I need ondismiss event. Plz help regarding this event.

  4. Isued this code

    document.addEventListener(‘onAdDismiss’, function(e){
    if(e.adType == ‘interstitial’) {
    interstitialReady = false;
    AdMob.prepareInterstitial({
    adId:options.adId,
    autoShow:false
    });
    }
    });

    it shows below error
    Property ‘adType’ does not exist on type ‘Event’.

    1. @ashraful haque, you’re trying wrong code. Try this instead:

        AdMob.onAdDismiss()
          .subscribe(() => { console.log('User dismissed ad'); });

      But then, if you put this code in place, you’ll start getting new ad once the user clicks on ‘close’ button of the previous ad. Then the application becomes meaningless.

      1. new ad once the user clicks on ‘close’

        that was not correct. I wanted to make interstitial but auto show off. Only will be shown when other page load again. Hope u understand

Leave a Reply

Your email address will not be published. Required fields are marked *