Facebook Native Ads: Ionic 2

Today lets implement Facebook Audience Network’s Native Advertisement in our Ionic 2 application.

Why Native Ad Unit?
A native ad is a custom designed unit that fits seamlessly with your app. If done well, ads can blend in naturally with your interface.

The unique feature of native ads is that they should balance your app’s experience while protecting the integrity of advertisers’ assets.

Related Read: Facebook Banner and Interstitial Ads: Ionic 2

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

Audience Network’s Native Ads: Ionic 2



YouTube Link: https://www.youtube.com/watch?v=-wfXpBGbvic [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 FacebookAds plugin
Step 2: Add Platform
Step 3: Implement Facebook Audience Network’s Native Ad into your Ionic 2 project
Step 4: Install your Ionic 2 app to your device to test Facebook Audience Network’s ads.

Native Advertising

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 our project folder.

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

Step 1: Install FacebookAds plugin

ionic plugin add cordova-plugin-facebookads

This installs FacebookAds 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, than 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 Facebook Ads into your Ionic 2 project

Native Advertisement

src/pages/home/home.ts

    platform.ready().then(() => {
      if(FacebookAds)
      {
        FacebookAds.createNativeAd('763416880384578_1139417452784517');
        this.start = 1;
      }
 
      document.addEventListener("onAdLoaded", function(data){
        let temp: any = data;
 
        if(temp.adType == "native")
        {
 
          document.getElementById('adIcon').setAttribute("src", temp.adRes.icon.url);
          document.getElementById('adCover').setAttribute("src", temp.adRes.coverImage.url);
          document.getElementById('adTitle').innerHTML = temp.adRes.title;
          document.getElementById('adBody').innerHTML = temp.adRes.body;
          document.getElementById('adSocialContext').innerHTML = temp.adRes.socialContext;
          document.getElementById('adBtn').innerHTML = temp.adRes.buttonText;
        }
 
      });
 
    });

Pass-in native ad units adId to createNativeAd() method. Now add a listener to onAdLoaded event. This event emits bunch of ad data, which we capture and embed into our view.

Here is the data structure(with Facebook Native Test Ad Data) of the emitted data.

 {
    "isTrusted":false,
    "adNetwork":"FacebookAds",
    "adEvent":"onAdLoaded",
    "adType":"native",
    "adId":"763416880384578_1139417452784517",
    "adRes":{"title":"Facebook Test Ad",
             "socialContext":"Get it on Google Play",
             "buttonText":"Install Now",
             "body":"Your ad integration works. Woohoo!",
             "coverImage":{ "url":"https://www.facebook.com/images/ads/network/test_video_banner.png",
                            "width":414,
                            "height":232},
             "icon":{"url":"https://scontent.xx.fbcdn.net/hphotos-xaf1/t39.3079-6/851551_836527893040166_1350205352_n.png",
                     "width":128,
                     "height":128
                     }
             }
}

We check to see if it is a native ad data. If so, we’ll further fetch and assign ad elements to view elements using Javascript.

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

import { Component } from '@angular/core';
 
import { NavController } from 'ionic-angular';
 
import { Platform } from 'ionic-angular';
 
declare var FacebookAds: any;
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 
 start: any = 0;
 
  constructor(public navCtrl: NavController, platform: Platform) {
    platform.ready().then(() => {
      if(FacebookAds)
      {
        FacebookAds.createNativeAd('763416880384578_1139417452784517');
        this.start = 1;
      }
 
      document.addEventListener("onAdLoaded", function(data){
        let temp: any = data;
 
        if(temp.adType == "native")
        {
 
          document.getElementById('adIcon').setAttribute("src", temp.adRes.icon.url);
          document.getElementById('adCover').setAttribute("src", temp.adRes.coverImage.url);
          document.getElementById('adTitle').innerHTML = temp.adRes.title;
          document.getElementById('adBody').innerHTML = temp.adRes.body;
          document.getElementById('adSocialContext').innerHTML = temp.adRes.socialContext;
          document.getElementById('adBtn').innerHTML = temp.adRes.buttonText;
        }
 
      });
 
    });
  }
}

Make sure to have global declaration of FacebookAds variable.

View Code: src/pages/home/home.html

  < span id="native" *ngIf="start != 0">
    < ion-card>
      < img src="" id="adCover" style="max-width: 100%; height: auto;" />
      < ion-card-content text-wrap>
        < ion-item>
          < ion-avatar item-left>
            < img src="" id="adIcon" />
          < /ion-avatar>
          < h2 id="adTitle">
          < p id="adBody">
        < /ion-item>
        < ion-row>
          < ion-col center text-left width-70 small style="font-size: x-small;">
            < span id="adSocialContext" small>< /span>
          < /ion-col>
          < ion-col center text-right width-30>
            < button ion-button small color="secondary" id="adBtn">
            < /button>
          < /ion-col>
        < /ion-row>
      < /ion-card-content>
    < /ion-card>
  < /span>

Here am adding a simple ion-card item with cover image and ion-avatar. We’ve added id’s to each of the elements and will fill the value once the ad data is emitted by onAdLoaded event.

Important Note: This is part 1 of implementing Native Ad. Next we need to implement Clickable area of the ad by using setNativeAdClickArea(adId, x, y, w, h) method. If anyone of you have implemented the Clickable area code for Native Ad, then kindly share your knowledge in the comment section – that would help a lot of us.

I’ve implemented Facebook Native Ads Clickable Area: Ionic 2.

Step 4: Install your Ionic 2 app to your device to test Facebook Audience Network 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 declared FacebookAds variable at the top of the component file.
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 plugins work only on the real devices, so do not try to test it using browsers.

I’ve implemented Facebook Native Ads Clickable Area: Ionic 2.

Facebook Banner and Interstitial Ads: Ionic 2

Today lets implement Facebook Audience Network’s Banner Ads and Interstitial Ads in our Ionic 2 project.

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

Audience Network’s Banner Ads and Interstitial Ads: Ionic 2



YouTube Link: https://www.youtube.com/watch?v=nU5iUw3xwz4 [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 FacebookAds plugin
Step 2: Add Platform
Step 3: Implement Facebook Audience Network’s Ads into your Ionic 2 project
Step 4: Install your Ionic 2 app to your device to test Facebook Audience Network’s ads.

Facebook Audience Network Ads Ionic2

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 our project folder.

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

Step 1: Install FacebookAds plugin

ionic plugin add cordova-plugin-facebookads

This installs FacebookAds 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 Facebook Ads 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

   if(FacebookAds)
      {
        let options = {
          adId: '763416880384578_1088816394511290',
          adSize: 'SMART_BANNER',
          isTesting: false,
          autoShow: true
        };
        FacebookAds.createBanner(options, function(data){
          FacebookAds.showBanner(8);
        }, function(err){});
      }

Pass configuration information to createBanner() method as first parameter. Second parameter is a success callback and third parameter is an error callback. Inside success callback, we can call showBanner() method which takes position number as a parameter.

isTesting – takes boolean value. It is set to true while development and set to false in production. Default value is false.

FacebookAds Object Value

{
"AD_SIZE":
    {
        "SMART_BANNER":"SMART_BANNER",
        "BANNER":"BANNER",
        "MEDIUM_RECTANGLE":"MEDIUM_RECTANGLE",
        "FULL_BANNER":"FULL_BANNER",
        "LEADERBOARD":"LEADERBOARD",
        "SKYSCRAPER":"SKYSCRAPER"},
 "AD_POSITION":
    {
        "NO_CHANGE":0,
        "TOP_LEFT":1,
        "TOP_CENTER":2,
        "TOP_RIGHT":3,
        "LEFT":4,
        "CENTER":5,
        "RIGHT":6,
        "BOTTOM_LEFT":7,
        "BOTTOM_CENTER":8,
        "BOTTOM_RIGHT":9,
        "POS_XY":10
    }
}

Configure your FacebookAds options using above values.

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 { HomePage } from '../pages/home/home';
 
declare var FacebookAds: any;
 
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage = HomePage;
  constructor(platform: Platform) {
    platform.ready().then(() => {
      if(FacebookAds)
      {
        let options = {
          adId: '763416880384578_1088816394511290',
          adSize: 'SMART_BANNER',
          isTesting: false,
          autoShow: true
        };
        FacebookAds.createBanner(options, function(data){
          FacebookAds.showBanner(8);
        }, function(err){
          console.log(JSON.stringify(err));
        });
      }
    });
  }
}

Make sure to declare FacebookAds variable(of type any) at the top.

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(){
    if(FacebookAds)
    {
      let options = {
        adId: '763416880384578_900057893387142'
      };
      FacebookAds.prepareInterstitial(options, function(data){
        FacebookAds.showInterstitial();
      }, function(err){})
    }
  };

we pass interstitial ad units adId to prepareInterstitial() method and then once the success callback is returned we invoke showInterstitial() method.

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

import { Component } from '@angular/core';
 
import { NavController } from 'ionic-angular';
 
import { Platform } from 'ionic-angular';
 
declare var FacebookAds: any;
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 
 
  constructor(public navCtrl: NavController, platform: Platform) {
    platform.ready().then(() => {});
  }
  loadAd(){
    if(FacebookAds)
    {
      let options = {
        adId: '763416880384578_900057893387142'
      };
      FacebookAds.prepareInterstitial(options, function(data){
        FacebookAds.showInterstitial();
      }, function(err){})
    }
  };
}

Make sure to declare FacebookAds variable at the top of home component.

other methods:

FacebookAds.removeBanner();
FacebookAds.showBannerAtXY(x, y);
FacebookAds.hideBanner();

Step 4: Install your Ionic 2 app to your device to test Facebook Audience Network 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 declared FacebookAds variable at the top of the component file.
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 plugins work only on the real devices, so do not try to test it using browsers.

Getting Started With IONIC APP

Let us learn the basics of IONIC today. We know that IONIC 2 is already in its Beta, and is being received well by the developer community. But we do not want to leave behind people using ionic versions below 2.

What is IONIC?
Ionic is a beautiful, open source front-end SDK for developing hybrid mobile apps with web technologies.
Web technologies like angular, HTML5, CSS.

Topics covered
1. Ionic commands.
2. Ionic templates – tabs, sidemenu, blank.
3. Ionic project folder structure.
4. Basic Dependency plugins.
5. Running our application in web browser.
6. Installing platform android to our project.
7. Building the application.
8. Running our application in android emulator.
9. Running our application in real mobile device.
10. USB debugging, Environment variable setting etc.

Software Versions used for the demo
1. Node: v4.2.6
2. Cordova: 6.0.0
3. Ionic: 1.7.14
4. android : Android 6.0 (API level 23)
5. OS: Demo showed on Windows 10 Operating System.

How to get android sdk installation details on Windows using command prompt?
1. Go to Run, open command prompt by typing cmd
2. Type this command android list targets
And you’ll get the list of all the installation and their basic details.

OR

“ionic info” command

C:\technotip\myApp1>ionic info
 
Your system information:
 
Cordova CLI: 6.0.0
Gulp version:  CLI version 3.9.0
Gulp local:
Ionic Version: 1.2.4
Ionic CLI Version: 1.7.14
Ionic App Lib Version: 0.7.0
OS:
Node Version: v4.2.6

Let’s start with the project



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



Software Installation
1. Install Node.js if you have not already.
2. Install cordova and ionic globally using the following command.

npm install -g cordova ionic

This will take some time to install cordova and ionic. To know more about npm(Node Package Manager), check External Module( NPM ) Install, Update, Remove: Node.js

Ionic Templates
There are 3 pre-designed templates ionic gives us to start the project
1. sidemenu
2. tabs
3. blank

For this tutorial I’ll be demonstrating using tabs template. All the explanation shown in the video applies to other templates too.

Start Project with tabs template

ionic start app_name tabs

All ionic commands start with the keyword ionic. Let us call our application as myApp1, so the command will be

c:/>cd technotip
c:/technotip>ionic start myApp1 tabs

Similarly, for sidemenu

ionic start myApp1 sidemenu

for blank

ionic start myApp1 blank

Downloading the project files
Once we run ionic start myApp1 tabs command, all the necessary files will be downloaded to our project folder(myApp1 folder) from ionic official git repository. Know that it’ll take some time to download these files – depending on your internet connection speed.

Once the files are downloaded, we need to get inside our project folder to execute ionic commands ..

c:/>cd technotip
c:/technotip>cd myApp1
c:/technotip/myApp1>

File structure


ionic file structure

plugins folder has plugins on which our project depends on, for some services.
www folder has all our files – like, templates, js files, css files and ionic library files
config.xml file is an important file and we’ll cover it in detail in another video tutorial

android sdk / android studio
Download android studio from Google Developer Site and install it without fail.

(I’m demonstrating for android platform, for iOS, use MAC and replace android keyword with ios in below ionic commands.)

Run the project
1. on browser using the command

ionic serve

use -l option to get additional log information + to launch ionic labs

ionic serve -l

You can enable chrome inspector and check how your app would look inside various devices. Use CTRL+SHIFT+i to open chrome inspector. Then use CTRL+SHIFT+M to open the device view mode.

2. add platform android

ionic platform add android

OR

cordova platform add android

3. Build the project

ionic build android

4. on emulator

ionic emulate android

emulator would take a lot of time to start and display your application. And usually it’s very slow to operate. Simply know this option but never use it for real serious development. For development purpose make sure to check the app using real device.

5. on real mobile device

ionic run android

use -l option to get additional log details + to launch ionic labs

ionic run android -l

Nexus USB Debugging
Connect your mobile phone(preferably nexus device) using USB cable. Turn on ‘Developer’ option and usb debugging option in your phone.
settings – Developer options ( enable it ) – ( scroll down ) – USB debugging ( enable it).

Environment variables
Note: I’m using Windows 10 operating system.

ANDROID_HOME=C:\Users\user_name\AppData\Local\Android\android-sdk
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_45

Check the file paths of the environment variable and change the path depending on the versions installed.

..other commands
1. Get plugin list

cordova plugin list

2. to exit ionic server

CTRL + C

3. whitelist plugin
Whitelist plugin gets installed by default when you create an ionic application. After that insert this piece of code inside head tag of index.html

     <meta http-equiv="Content-Security-Policy" 
           content="default-src *; style-src 'self' 'unsafe-inline'; 
           script-src 'self' 'unsafe-inline' 'unsafe-eval'"/>

Troubleshoot
Let us know what problems you’re facing and we’ll try our best to solve it for you ..please give us proper log information, so that we can understand the problem.

Sharing Is Caring ..
Please share this article with your friends/colleagues on your social profile ..thanks
Hope it helps