Using Ionic Native: Ionic 2

Today lets learn about an important project which helps us use 130+ native mobile SDK features in our Ionic application through simple JavaScript interfaces – Ionic Native.

ionic native ionic2

Ionic Native is a TypeScript wrapper for Cordova/PhoneGap plugins that make adding any native functionality you need to your Ionic 2 mobile app easy. Ionic Native wraps plugin callbacks in a Promise or an Observable, providing a common interface for all plugins and ensuring that native events trigger change detection in Angular 2.

Related Read:
Ionic 2 Starter Templates.
Adding AdMob In Ionic 2.

Using ‘Ionic Native’ In Ionic 2 Applications


[youtube https://www.youtube.com/watch?v=SM54loG63ks]

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



There are two steps required to use Ionic Native in our project
1. Install the Ionic Native package for each plugin you want to add.
2. Install the plugin using Cordova or Ionic CLI.

For example:
If we want to add AdMob plugin to our application:
Step 1: Add/ Install Specific Ionic Native package

npm install --save @ionic-native/ad-mob

Step 2: Add / install the plugin using Cordova or Ionic CLI.

ionic plugin add cordova-plugin-admobpro

Additional Implementation
Listing Plugin Class as Provider: src/app/app.module.ts

import { AdMob } from '@ionic-native/ad-mob';
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
 
 
 
@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    AdMob,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

Look at the first import statement in above code snippet. We import AdMob plugin and the way we import is specific to ad-mob and we do not import the whole ionic native script here – thus saving application load time.

Also specify the class name as provider. Because we use the services provided by this class in our application.

Working of plugin: src/app/app.component.ts

import { AdMob } from '@ionic-native/ad-mob';
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
 
import { HomePage } from '../pages/home/home';
 
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = HomePage;
 
  constructor(public admob: AdMob, platform: Platform) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
 
      this.admob.createBanner({
        adId: 'ca-app-pub-5732334124058455/4262868443',
        isTesting: false,
        autoShow: false
      }).then(() => {
        this.admob.showBanner(8);
      });
 
    });
  }
}

Again, we import AdMob native code wherever we want to implement the service of this plugin. We create instance of the class we want to implement – as constructor argument. Then inside platform.ready() method we call the methods of these classes and implement its services inside our project.

Trouble Shoot
1. If you’re getting ‘plugin not found‘ error. OR Cannot find module “@ionic-native/ “ errors, then follow below commands to fix it.

npm rebuild
npm install

2. Error Message “Provider Not Found:
Make sure to include all the specific packages inside src/app/app.module.ts file and list its class name inside providers array.

Adding AdMob In Ionic 2

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


[youtube https://www.youtube.com/watch?v=Dj2n_25hcko]

YouTube Link: https://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.