Ionic 2 comes with Ionic Storage library which makes use of storage engines based on its availability and its priority. For example, in native device it uses SQLite if available, if not it’ll fall back to use localstorage or IndexedDB – again, based on its availability. If the app is being run in the web or as a Progressive Web App, Storage will attempt to use IndexedDB, WebSQL, and localstorage, in that order.
Update:
Ionic has made slight changes in how your import Ionic Storage inside app.module.ts file. You can find it at Ionic Storage Module: Ionic 2. Other than how you import Ionic Storage in app.module.ts file, everything is same as present in this(Ionic Storage: Ionic 2) video tutorial.
In this video lets learn how to store and retrieve JSON data in array format using Ionic 2 Storage with a very simple example.
localstorage, WebSQL and IndexedDB Since Ionic uses browser to render the application, we have access to browser based storage engines like localstorage, WebSQL and IndexedDB. But these storage engines are not reliable. If the device is running on low disk-space and the operating system decides to clear some data, then it might even clear the data stored in these storage engines.
SQLite SQLite is query based RDBMS like Storage System for Mobile Devices. You can create, read, update and delete records just like in RDBMS. If you want to store/persist serious data locally, then you can relay on SQLite. Ionic 2 doesn’t ship with this by default – we can use cordova plugin to make use of SQLite.
cordova plugin add cordova-sqlite-storage
cordova plugin add cordova-sqlite-storage
Once we install this cordova plugin, Ionic 2 Storage library will priorities SQLite and make use of it instead of localstorage or IndexedDB.
Remember, Ionic Storage uses SQLite only on the native device. If you run the same application on the web maybe as a Progressive Web App, Ionic Storage will switch to use IndexedDB, WebSQL, and localstorage, in that order.
Make sure to import the library first inside home.ts component. Next, create a reference variable for Storage class. Now access the get method of Storage class. Using get method, get the value assocated with the given key. This returns a promise. Once the promise is resolved we get the stored data. If the key is being used for the first time and nothing has been stored yet, then it returns null.
Set Data: src/pages/home/home.ts
this.storage.set('myStore', value);
this.storage.set('myStore', value);
Set the value for the given key. In my case, am using a key called myStore.
First we import the Storage library at the top. Next create a reference variable called storage. Inside the constructor we get / fetch the stored data and assign it to a variable called items, which we iterate through and display on the home.html view.
save() method When the user enters some data in the input field(on the view – home.html) and submits, we check the previously stored data, if present, retrieve it, append the new data and then stored / set it back to the same key.
Here we iterate through the variable items and then display individual array item on the view. We also have a input field where user enters company name and once he/she hits on Add button the data gets saved in storage engine via Ionic 2 Storage.
Other Member functions of Ionic 2 Storage Class remove(key); – Remove any value associated with this key. clear(); – Clears the entire key value store. (Be very careful while using it.) length(); – returns the number of keys stored. keys(); – returns the keys in the store. forEach(iteratorCallback) – Iterate through each key,value pair.
Today lets learn how to code the clickable area of Facebook Native Ad Unit. Before proceeding with today’s tutorial, please visit yesterdays tutorial and learn how to request and display the Native Ad creative inside Ionic 2 application.
In todays video tutorial lets learn: 1. Removing top left corner green patch – clickable area problem. 2. Aligning the clickable area to the Native Ad Unit creative properly. 3. Make sure the top left corner clickable area doesn’t appear once again when we change the device orientation. 4. Removing clickable area once the user switches to other views. 5. Why doesn’t your app show Facebook Native Ads all the time – why is fill rate low?
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.
updateXY() method src/pages/home/home.ts
updateXY(left, top){
var h, w, x, y;
var d = document.getElementById('native');
w = d.clientWidth;
h = d.clientHeight;
x = d.offsetLeft - left;
y = d.offsetTop - top;
if(FacebookAds)
FacebookAds.setNativeAdClickArea('763416880384578_1139417452784517', x, y, w, h);
};
updateXY(left, top){ var h, w, x, y; var d = document.getElementById('native'); w = d.clientWidth; h = d.clientHeight; x = d.offsetLeft - left; y = d.offsetTop - top; if(FacebookAds) FacebookAds.setNativeAdClickArea('763416880384578_1139417452784517', x, y, w, h); };
Here we dynamically fetch the ad display containers width and height, and then x and y axis values of the display component.
When we scroll the application vertically only y value changes and x value remains constant, when we scroll the view horizontally x value changes and y value remains constant. In most of the application scrolling will only be available vertically.
Finally, we pass x, y, w, h value to setNativeAdClickArea() method along with the Native Ad Units ID as its first parameter.
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, public platform: Platform) {
platform.ready().then(() => {
});
};
updateXY(left, top){
var d;
var h, w, x, y;
d = document.getElementById('native');
w = document.getElementById('native').clientWidth;
h = document.getElementById('native').clientHeight;
x = d.offsetLeft - left;
y = d.offsetTop - top;
if(FacebookAds)
FacebookAds.setNativeAdClickArea('763416880384578_1139417452784517', x, y, w, h);
};
ionViewDidEnter(){
this.platform.ready().then(() => {
if(FacebookAds)
{
FacebookAds.createNativeAd('763416880384578_1139417452784517', function(data){
document.addEventListener("onAdLoaded", function(data){
let temp: any = data;
if(temp.adType == "native")
{
document.getElementById('adIcon').setAttribute("src", decodeURIComponent(temp.adRes.icon.url));
document.getElementById('adCover').setAttribute("src", decodeURIComponent(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;
}
});
}, function(err) { alert(JSON.stringify(err)); });
}
});
};
}
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, public platform: Platform) { platform.ready().then(() => { }); }; updateXY(left, top){ var d; var h, w, x, y; d = document.getElementById('native'); w = document.getElementById('native').clientWidth; h = document.getElementById('native').clientHeight; x = d.offsetLeft - left; y = d.offsetTop - top; if(FacebookAds) FacebookAds.setNativeAdClickArea('763416880384578_1139417452784517', x, y, w, h); }; ionViewDidEnter(){ this.platform.ready().then(() => { if(FacebookAds) { FacebookAds.createNativeAd('763416880384578_1139417452784517', function(data){ document.addEventListener("onAdLoaded", function(data){ let temp: any = data; if(temp.adType == "native") { document.getElementById('adIcon').setAttribute("src", decodeURIComponent(temp.adRes.icon.url)); document.getElementById('adCover').setAttribute("src", decodeURIComponent(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; } }); }, function(err) { alert(JSON.stringify(err)); }); } }); };
}
Now we need to access the view scrolling by the user and then dynamically determine the updated x, y coördinates, so that we can update the current clickable area.
Content Reference To get reference to the content component from a pages logic, we can use angular’s @ViewChild annotation and create a variable of type Content and subscribe to its scrolling event. And then pass the x(left offset) and y(top offset) values of the screen to UpdateXY() method, so that it can determine the current position of the Native Ad Unit Creative on the mobile screen.
src/pages/home/home.ts
import { Component, ViewChild } from '@angular/core';
import { NavController, Content } from 'ionic-angular';
import { Platform } from 'ionic-angular';
declare var FacebookAds: any;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild(Content) content: Content;
constructor(public navCtrl: NavController, public platform: Platform) {
platform.ready().then(() => {
this.content.ionScroll.subscribe((data) => {
this.updateXY(data.scrollLeft, data.scrollTop);
});
});
};
updateXY(left, top){
var d;
var h, w, x, y;
d = document.getElementById('native');
w = document.getElementById('native').clientWidth;
h = document.getElementById('native').clientHeight;
x = d.offsetLeft - left;
y = d.offsetTop - top;
if(FacebookAds)
FacebookAds.setNativeAdClickArea('763416880384578_1139417452784517', x, y, w, h);
};
ionViewDidEnter(){
this.platform.ready().then(() => {
if(FacebookAds)
{
FacebookAds.createNativeAd('763416880384578_1139417452784517', function(data){
document.addEventListener("onAdLoaded", function(data){
let temp: any = data;
if(temp.adType == "native")
{
document.getElementById('adIcon').setAttribute("src", decodeURIComponent(temp.adRes.icon.url));
document.getElementById('adCover').setAttribute("src", decodeURIComponent(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;
}
});
}, function(err) { alert(JSON.stringify(err)); });
}
});
};
}
import { Component, ViewChild } from '@angular/core';
import { NavController, Content } from 'ionic-angular';
import { Platform } from 'ionic-angular';
declare var FacebookAds: any;
@Component({ selector: 'page-home', templateUrl: 'home.html'
})
export class HomePage { @ViewChild(Content) content: Content; constructor(public navCtrl: NavController, public platform: Platform) { platform.ready().then(() => { this.content.ionScroll.subscribe((data) => { this.updateXY(data.scrollLeft, data.scrollTop); }); }); }; updateXY(left, top){ var d; var h, w, x, y; d = document.getElementById('native'); w = document.getElementById('native').clientWidth; h = document.getElementById('native').clientHeight; x = d.offsetLeft - left; y = d.offsetTop - top; if(FacebookAds) FacebookAds.setNativeAdClickArea('763416880384578_1139417452784517', x, y, w, h); }; ionViewDidEnter(){ this.platform.ready().then(() => { if(FacebookAds) { FacebookAds.createNativeAd('763416880384578_1139417452784517', function(data){ document.addEventListener("onAdLoaded", function(data){ let temp: any = data; if(temp.adType == "native") { document.getElementById('adIcon').setAttribute("src", decodeURIComponent(temp.adRes.icon.url)); document.getElementById('adCover').setAttribute("src", decodeURIComponent(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; } }); }, function(err) { alert(JSON.stringify(err)); }); } }); };
}
With this code we start getting a nice Native Ad creative, but with a clickable area at the top left corner of the screen. That is because updateXY() method is called only when the user scrolls the screen. So we need to call updateXY() once the view is loaded. Lets pass (0, 0) as (x, y) value to updateXY() as there is no changes in the x, y coördinates initially when the app is loaded. We call updateXY() method inside ionViewDidEnter() method, once the Native Ad emits some data.
src/pages/home/home.ts
import { Component, ViewChild } from '@angular/core';
import { NavController, Content } from 'ionic-angular';
import { Platform } from 'ionic-angular';
declare var FacebookAds: any;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild(Content) content: Content;
constructor(public navCtrl: NavController, public platform: Platform) {
platform.ready().then(() => {
this.content.ionScroll.subscribe((data) => {
this.updateXY(data.scrollLeft, data.scrollTop);
});
});
};
updateXY(left, top){
var d;
var h, w, x, y;
d = document.getElementById('native');
w = document.getElementById('native').clientWidth;
h = document.getElementById('native').clientHeight;
x = d.offsetLeft - left;
y = d.offsetTop - top;
if(FacebookAds)
FacebookAds.setNativeAdClickArea('763416880384578_1139417452784517', x, y, w, h);
};
ionViewDidEnter(){
var that = this;
this.platform.ready().then(() => {
if(FacebookAds)
{
FacebookAds.createNativeAd('763416880384578_1139417452784517', function(data){
document.addEventListener("onAdLoaded", function(data){
let temp: any = data;
if(temp.adType == "native")
{
document.getElementById('adIcon').setAttribute("src", decodeURIComponent(temp.adRes.icon.url));
document.getElementById('adCover').setAttribute("src", decodeURIComponent(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;
that.updateXY(0, 0);
}
});
}, function(err) { alert(JSON.stringify(err)); });
}
});
};
}
import { Component, ViewChild } from '@angular/core';
import { NavController, Content } from 'ionic-angular';
import { Platform } from 'ionic-angular';
declare var FacebookAds: any;
@Component({ selector: 'page-home', templateUrl: 'home.html'
})
export class HomePage { @ViewChild(Content) content: Content; constructor(public navCtrl: NavController, public platform: Platform) { platform.ready().then(() => { this.content.ionScroll.subscribe((data) => { this.updateXY(data.scrollLeft, data.scrollTop); }); }); }; updateXY(left, top){ var d; var h, w, x, y; d = document.getElementById('native'); w = document.getElementById('native').clientWidth; h = document.getElementById('native').clientHeight; x = d.offsetLeft - left; y = d.offsetTop - top; if(FacebookAds) FacebookAds.setNativeAdClickArea('763416880384578_1139417452784517', x, y, w, h); }; ionViewDidEnter(){ var that = this; this.platform.ready().then(() => { if(FacebookAds) { FacebookAds.createNativeAd('763416880384578_1139417452784517', function(data){ document.addEventListener("onAdLoaded", function(data){ let temp: any = data; if(temp.adType == "native") { document.getElementById('adIcon').setAttribute("src", decodeURIComponent(temp.adRes.icon.url)); document.getElementById('adCover').setAttribute("src", decodeURIComponent(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; that.updateXY(0, 0); } }); }, function(err) { alert(JSON.stringify(err)); }); } }); };
}
Here we invoke updateXY(0, 0) initially once the view is loaded i.e., before the user actually scrolls the view area. This removes the top left green clickable area patch. But then there is misplaced clickable area. Looks like the area misplaced is equal to the height of the header element.
Note: Am using that.updateXY() to invoke member function instead of this.updateXY(). To know why I replaced the keyword this in order to invoke member function: setTimeout and setInterval methods: Ionic 2
src/pages/home/home.ts
import { Component, ViewChild } from '@angular/core';
import { NavController, Content } from 'ionic-angular';
import { Platform } from 'ionic-angular';
declare var FacebookAds: any;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild(Content) content: Content;
constructor(public navCtrl: NavController, public platform: Platform) {
platform.ready().then(() => {
this.content.ionScroll.subscribe((data) => {
this.updateXY(data.scrollLeft, data.scrollTop);
});
});
};
updateXY(left, top){
var d;
var h, w, x, y;
d = document.getElementById('native');
var headHeight = document.getElementById("headerHeight").clientHeight;
w = document.getElementById('native').clientWidth;
h = document.getElementById('native').clientHeight;
x = d.offsetLeft - left;
y = d.offsetTop - (top - headHeight);
if(FacebookAds)
FacebookAds.setNativeAdClickArea('763416880384578_1139417452784517', x, y, w, h);
};
ionViewDidEnter(){
var that = this;
this.platform.ready().then(() => {
if(FacebookAds)
{
FacebookAds.createNativeAd('763416880384578_1139417452784517', function(data){
document.addEventListener("onAdLoaded", function(data){
let temp: any = data;
if(temp.adType == "native")
{
document.getElementById('adIcon').setAttribute("src", decodeURIComponent(temp.adRes.icon.url));
document.getElementById('adCover').setAttribute("src", decodeURIComponent(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;
that.updateXY(0, 0);
}
});
}, function(err) { alert(JSON.stringify(err)); });
}
});
};
}
import { Component, ViewChild } from '@angular/core';
import { NavController, Content } from 'ionic-angular';
import { Platform } from 'ionic-angular';
declare var FacebookAds: any;
@Component({ selector: 'page-home', templateUrl: 'home.html'
})
export class HomePage { @ViewChild(Content) content: Content; constructor(public navCtrl: NavController, public platform: Platform) { platform.ready().then(() => { this.content.ionScroll.subscribe((data) => { this.updateXY(data.scrollLeft, data.scrollTop); }); }); }; updateXY(left, top){ var d; var h, w, x, y; d = document.getElementById('native'); var headHeight = document.getElementById("headerHeight").clientHeight; w = document.getElementById('native').clientWidth; h = document.getElementById('native').clientHeight; x = d.offsetLeft - left; y = d.offsetTop - (top - headHeight); if(FacebookAds) FacebookAds.setNativeAdClickArea('763416880384578_1139417452784517', x, y, w, h); }; ionViewDidEnter(){ var that = this; this.platform.ready().then(() => { if(FacebookAds) { FacebookAds.createNativeAd('763416880384578_1139417452784517', function(data){ document.addEventListener("onAdLoaded", function(data){ let temp: any = data; if(temp.adType == "native") { document.getElementById('adIcon').setAttribute("src", decodeURIComponent(temp.adRes.icon.url)); document.getElementById('adCover').setAttribute("src", decodeURIComponent(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; that.updateXY(0, 0); } }); }, function(err) { alert(JSON.stringify(err)); }); } }); };
}
Go to home.html and assign id of headerHeight to the ion-header tag. Now get its clientHeight and subtract it from the current scrollTop of the screen – inside updateXY() method.
On Device Orientation Change The top left corner green clickable area spot appears once again when the device orientation is changed. To deal with that lets add a listener for orientation change and then call updateXY() method. src/pages/home/home.ts
window.addEventListener('orientationchange', function(data){
if(data.isTrusted == 1)
{
this.updateXY(0, 0);
// You can also get the values of x, y, w, h using javascript and then
// assign it to the clickablearea method of FacebookAds.
}
});
window.addEventListener('orientationchange', function(data){ if(data.isTrusted == 1) { this.updateXY(0, 0); // You can also get the values of x, y, w, h using javascript and then // assign it to the clickablearea method of FacebookAds. } });
Remove Native Ad Important: Remove the Native Ad(along with the clickable area) once the user navigates away from the current(Native Ad) view. src/pages/home/home.ts
Make sure to call removeNativeAd() method inside ionViewDidLeave() method in order to remove the Native Ad. Other wise, the clickable area still persists and when user clicks on any other app elements the ad gets triggered and this is against Facebooks(or any other adnetworks) ad policy. So in order to play safe and avoid policy violation or termination of your Facebook Audience Network account, make sure you remove the native ad once the user navigates away from that view.
Important Note Make sure you pass the same native ad units ID to all 3 methods:
var adId = ‘763416880384578_1139417452784517’; FacebookAds.createNativeAd(adId); FacebookAds.setNativeAdClickArea(adId, x, y, w, h); FacebookAds.removeNativeAd(adId);
Still Clickable area is misplaced or not appearing? Sometimes I observed that the clickable area doesn’t work properly in test mode. But the same code works perfectly while displaying real ads. So if you have set isTesting to true, then make it false.
How to get Test Ads? You can simply put this code inside your constructor(wrap it around by platform ready method)
This show start showing test ads, as FacebookAds variable is a global variable to that component. Make sure to change the value of isTesting to false while moving to production or you can simply remove the code if you’re not showing Facebook audience networks banner ads in your application.
Why is my fill rate less than 100% ? Fill rate refers the number of ads Facebook return compared to the number of ads you request. There are several reasons why not all requests are filled:
The person using your app hasn’t logged into the Facebook app in the last 30 days, or the person on your mobile website isn’t logged into Facebook in the same browser. In order to show targeted ads, Audience Network needs to be able to match each person to his or her Facebook profile. Without this match, it can’t fill the request.
The person using your app or site has turned off targeted advertising in his or her device settings.
Your app or site has requested too many ads in a short period of time. Audience Network limits ad delivery to a maximum of 25 ads served per 30 minutes to a single person. Facebook also limit ad delivery if your app or site requests more than one ad for the same banner placement within 15 seconds.
Facebook couldn’t find a relevant ad that matches the targeting and interests of the person using your app or site. Check your filters to make sure you aren’t excluding too many possible advertisers.
Fallback Ad Network In order to make sure you get near to 100% fill of your ad spot, we need to have a fallback ad network. If Facebooks Audience Network doesn’t have ads to serve to a particular user, then we can invoke some other(alternative/fallback) ad networks Native Ad and fill the ad spot. I’ll be showing it in upcoming video tutorials. Stay subscribed to our blog and our YouTube Channel.
Example Application We have implemented Facebook Audience Network in one of our applications: RSS Reader You can use this app to subscribe and keep track of the content you love. You can also subscribe to our blog using the app.
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.
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
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.
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.
This installs FacebookAds plugin to our Ionic 2 project.
Step 2: Add Platform
ionic platform add android
OR
ionic platform add ios
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
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
}
}
}
{ "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.
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.
Step 4: Install your Ionic 2 app to your device to test Facebook Audience Network ads
ionic run android -l -c
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 rm android
ionic platform add 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.
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
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.
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.
This installs FacebookAds plugin to our Ionic 2 project.
Step 2: Add Platform
ionic platform add android
OR
ionic platform add ios
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
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.
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.
Step 4: Install your Ionic 2 app to your device to test Facebook Audience Network ads
ionic run android -l -c
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 rm android
ionic platform add 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.
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
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
This installs AdMobPro plugin to our Ionic 2 project.
Step 2: Add Platform
ionic platform add android
OR
ionic platform add ios
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
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.
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.
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.
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
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 rm android
ionic platform add 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.