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
Ionic Native
You need to make little changes in plugin installation procedures. Watch Using Ionic Native: Ionic 2 video tutorial to know more.
Implementing AdMob Ads In Ionic 2
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.
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.
View Comments
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.
@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?
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);
@ashraful haque, Could you please let me know the values you are passing? That way I can let you know what value is wrong and how to correct it.
@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
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
@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.
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.
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'.
@ashraful haque, you're trying wrong code. Try this instead:
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.
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
Hi Satish,
Can you help me in ionic2 admob. Ads are not coming in my APP. But the testing ads are working fine. I am not able to solve the problem.. My app is live on google playstore..
Can you please help me.
My email id is --- akkii922@gmail.com
need your help..
Thanks in advance.
@Akshay, Still you're facing the problem? Have you put the correct ad unit ID while coding your app?
Hello, I was trying the above code you suggested to @ashraful haque:
AdMob.onAdDismiss()
.subscribe(() => { console.log('User dismissed ad'); });
but it gives me this error:
Property 'onAdFailLoad' does not exist on type 'typeof AdMob'.
could you please help me???
@Sasha, onAdFailLoad() is triggered when failed to receive Ad. On the other hand onAdDismiss() is triggered when you dismiss the Ad and back to your App. Your error message us about onAdFailLoad. Could you please check the code related to onAdFailLoad() method. The code you've posted is about onAdDismiss() method and it doesn't seem to have any error in it.
Thank you for the great tutorial, I have the add unit showing but there is no add. Here is my code:
constructor(platform: Platform) {
platform.ready().then(() => {
let options = {
adId: 'my-ad-id',
// adSize: 'SMART_BANNER',
isTesting: false
};
AdMob.createBanner(options).then(() => {
AdMob.showBanner(2);
});
});
}
Thanks!
@Josh, If you created the ad unit recently then it'll take some time to show up the ads. In my experience it doesn't show ads for atleast 5-10 minutes. Also pass 8 to showBanner and check it the ad appears at the bottom center of the application.
Thanks, great tutorial!!