admob doesn't show ads in my app with ionic 5 - ionic-framework

I am having problems with Admob not showing ads in my ionic app 5.
Can someone help me I will share the code I used
import { Injectable } from '#angular/core';
import { Platform } from '#ionic/angular';
import { AdMobFree, AdMobFreeBannerConfig, AdMobFreeInterstitialConfig, AdMobFreeRewardVideoConfig } from '#ionic-native/admob-free/ngx';
#Injectable({
providedIn: 'root'
})
export class AdmobService {
bannerConfig: AdMobFreeBannerConfig = {
isTesting: false,
autoShow: true,//,
id: "ca-app-pub-************************"
//id: "ID GENERATED AT ADMOB ca-app-pub FOR PROD"
};
//INTERSTITIAL CONFIG
interstitialConfig: AdMobFreeInterstitialConfig = {
isTesting: false,
autoShow: false,
id: "ca-app-pub-****************************",
//id: "ID GENERATED AT ADMOB ca-app-pub FOR PROD"
};
//REWARD VIDEO CONFIG.
//ADD PLATFORM Y ADMOB AT CONSTRUCTOR.
constructor(
public platform: Platform,
private admobFree: AdMobFree
) {
//LOAD ADS AT PLATFORM READY PROMISE.
platform.ready().then(()=>{
//BANNER
this.admobFree.banner.config(this.bannerConfig);
//INTERSTITIAL
this.admobFree.interstitial.config(this.interstitialConfig);
this.admobFree.interstitial.prepare().then(() => {
console.log('INTERSTIAL LOADED')
}).catch(e =>
console.log('PROBLEM LOADING INTERSTITIAL: ', e)
);
//REWARD VIDEO
});
}
ShowBanner() {
//CHECK AND SHOW BANNER
this.admobFree.banner.prepare().then(() => {
console.log('BANNER LOADED')
}).catch(e =>
console.log('PROBLEM LOADING BANNER: ', e)
);
}
ShowInterstitial() {
//CHECK AND SHOW INTERSTITIAL
this.admobFree.interstitial.isReady().then(() => {
//AT .ISREADY SHOW
this.admobFree.interstitial.show().then(() => {
console.log('INTERSTITIAL LOADED')
})
.catch(e => console.log('PROBLEM LOADING REWARD VIDEO: ', e) );
})
.catch(e => console.log('PROBLEM LOADING REWARD VIDEO: ', e) );
}
}

need the app to be published on google play for ads to appear?

Related

PushNotifications stop working after installing Community/FCM plugin

I am currently using ionic capacitor PushNotifications for Firebase cloud messaging. By the help of this I can get tokens.
Now I want to send notifications to all app users so I decided to use topics.
For this, I installed community/FCM plugin.
capacitor-community/fcm
I also made suggested changes in the MainActivity.java file, no error during app build.
But after installation this FCM plugin, PushNotifications(token) stop working.
Even below code starts always retuning false.
if (isPushNotificationsAvailable) {
this.initPushNotifications();
}
Here is my MainActivity.java file:-
package io.ionic.starter;
import com.getcapacitor.community.fcm.FCMPlugin;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;
import java.util.ArrayList;
public class MainActivity extends BridgeActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initializes the Bridge
this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
// Additional plugins you've installed go here
// Ex: add(TotallyAwesomePlugin.class);
add(FCMPlugin.class);
}});
}
}
Here my fcm.service.ts File:-
import { Component, Injectable } from '#angular/core';
import { Capacitor } from '#capacitor/core';
import { Router } from '#angular/router';
import { Storage } from '#ionic/storage';
import {
ActionPerformed,
PushNotificationSchema,
PushNotifications,
Token
} from '#capacitor/push-notifications';
// import { FCM } from '#capacitor-community/fcm';
const isPushNotificationsAvailable = Capacitor.isPluginAvailable('PushNotifications');
#Injectable({
providedIn: 'root'
})
export class FcmService {
public topicName = 'project';
constructor(
private router: Router,
private storage: Storage
) { }
initPush() {
//This Plugin is not available on web
if (isPushNotificationsAvailable) {
this.initPushNotifications();
}
}
// Request permission to use push notifications
// iOS will prompt user and return if they granted permission or not
// Android will just grant without prompting
private initPushNotifications() {
//console.log('Initializing HomePage');
PushNotifications.requestPermissions().then(result => {
if (result.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// Show some error
}
});
PushNotifications.addListener('registration', (token: Token) => {
alert('Push registration success, token: ' + token.value);
//Store Devive Token in session variable
this.storage.set("device_token", token.value);
// FCM.getToken()
// .then((r) => alert(`Token ${r.token}`))
// .catch((err) => console.log(err));
// now you can subscribe to a specific topic
// FCM.subscribeTo({ topic: this.topicName })
// .then((r) => alert(`subscribed to topic`))
// .catch((err) => console.log(err));
});
PushNotifications.addListener('registrationError', (error: any) => {
//alert('Error on registration: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
(notification: PushNotificationSchema) => {
//alert('Push received: ' + JSON.stringify(notification));
},
);
PushNotifications.addListener(
'pushNotificationActionPerformed',
(notification: ActionPerformed) => {
// alert('Push action performed: ' + JSON.stringify(notification));
const data = notification.notification.data;
//console.log('Action performed: ' + JSON.stringify(notification.notification));
if (data.detailsId) {
this.router.navigate(['/bid-project', data.detailsId]);
}
},
);
}
//Reset all Badge count
// resetBadgeCount() {
// PushNotifications.removeAllDeliveredNotifications();
// }
// move to fcm demo
// subscribeTo() {
// PushNotifications.register()
// .then((_) => {
// FCM.subscribeTo({ topic: this.topicName })
// .then((r) => alert(`subscribed to topic ${this.topicName}`))
// .catch((err) => console.log(err));
// })
// .catch((err) => alert(JSON.stringify(err)));
// }
// unsubscribeFrom() {
// FCM.unsubscribeFrom({ topic: this.topicName })
// .then((r) => alert(`unsubscribed from topic ${this.topicName}`))
// .catch((err) => console.log(err));
// }
}
After removing community plugin token generation started working as before.
Please tell me what wrong is with my code.

How to get OneSignal Push Notification Device ID Ionic 3

I have implemented the push notification functionality in my ionic app but it is not working. I am not getting the register id after the app is deployed. Following is my code.
app.component.ts
constructor(public platform: Platform, public splashScreen: SplashScreen, public menu: MenuController,
private storage: StorageService,private toast: ToastService, public events: Events, private push: Push,
private alertCtrl: AlertController, public network: Network, private api: UserService) {
platform.ready().then(() => {
debugger
this.pushSetup();
this.userDetails = this.storage.getData('userDetails');
this.isAlertShown = false;
// this.task = setInterval(() => {
// this.checkInternet();
// }, 3000);
if (this.userDetails != undefined || this.userDetails != null) {
this.rootPage = 'welcome';
} else {
this.rootPage = 'login';
}
this.initializeApp();
});
pushSetup() {
console.log("inside pushSetup");
const options: PushOptions = {
android: {
senderID: '592660866764',
forceShow: 'true'
},
ios: {
alert: 'true',
badge: true,
sound: 'false'
}
};
console.log("inside pushSetup 1");
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => console.log('Received a notification', notification));
pushObject.on('registration').subscribe((registration: any) =>console.log('Received a notification', registration));
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
}
Install the Cordova and Ionic Native plugins:
ionic cordova plugin add onesignal-cordova-plugin
npm install --save #ionic-native/onesignal
insert in app.module.ts Onesignal
import { OneSignal } from '#ionic-native/onesignal';
providers: [
....
OneSignal
...
]
In App Component you needs One Signal App ID and Google Project ID
in app.component.ts:
import { OneSignal } from '#ionic-native/onesignal';
import { Platform } from 'ionic-angular';
constructor(public oneSignal: OneSignal,
private platform: Platform) { }
onseSignalAppId: string = 'YOUR_ONESIGNAL_APP_ID';
googleProjectId: string = 'YOUR_GOOGLE_PROJECT_ID';
if(this.platform.is('cordova')) {
if (this.platform.is('android')) {
this.oneSignal.startInit(this.onseSignalAppId, this.googleProjectId);
}
else if (this.platform.is('ios')) {
this.oneSignal.startInit(this.onseSignalAppId);
}
this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification);
this.oneSignal.handleNotificationReceived().subscribe(() => {
// do something when notification is received
});
this.oneSignal.handleNotificationOpened().subscribe(result => {
// do something when a notification is opened
});
this.oneSignal.endInit();
// AND THIS METHOD RETURN YOUR DEVICES USER_ID
this.oneSignal.getIds().then(identity => {
alert(identity.pushToken + ' it's PUSHTOKEN');
alert(identity.userId + 'it's USERID);
});
}

Geolocation not working in device ionic3

I am working with ionic 3 location-based work. I am not able to get current location of latitude and longitude here. I mentioned my usable code. It's working fine in browser level but not working in a mobile device.
code
$ ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"
$ npm install --save #ionic-native/geolocation
import { Geolocation } from '#ionic-native/geolocation';
constructor(private geolocation: Geolocation) {}
this.geolocation.getCurrentPosition().then((resp) => {
console.log( resp.coords.latitude)
console.log( resp.coords.longitude)
}).catch((error) => {
console.log('Error getting location', error);
});
Try this:
import { Geolocation } from '#ionic-native/geolocation';
import { Platform } from 'ionic-angular';
//Set the properties in this class
long: any; //longitude
lati: any; //latitude
constructor(private platform: Platform, private geolocation: Geolocation) {
this.platform.ready().then(()=>{
//set options..
var options = {
timeout: 20000 //sorry I use this much milliseconds
}
//use the geolocation
this.geolocation.getCurrentPosition(options).then(data=>{
this.long = data.coords.longitude;
this.lati = data.coords.latitude;
}).catch((err)=>{
console.log("Error", err);
});
});
}
Let this be in the constructor. Don't forget to agree to the location privacy permission, also enable location option on your Android device(this is probable though).
Try to call the geolocation function inside ionViewDidLoad() or ngAfterViewInit() method.
import { Geolocation } from '#ionic-native/geolocation';
constructor(private geolocation: Geolocation) {}
ngAfterViewInit(){
this.geolocation.getCurrentPosition().then((resp) => {
console.log( resp.coords.latitude)
console.log( resp.coords.longitude)
}).catch((error) => {
console.log('Error getting location', error);
});
}
I hope this will solve your problem!
import { Geolocation } from '#ionic-native/geolocation';
import { Platform } from 'ionic-angular';
//Set the properties in this class
long: any; //longitude
lati: any; //latitude
constructor(private platform: Platform, private geolocation: Geolocation) {
this.platform.ready().then(()=>{
//set options..
var options = {
enableHighAccuracy: true, timeout: 60000, maximumAge: 0
};
//use the geolocation
this.geolocation.getCurrentPosition(options).then(data=>{
this.long = data.coords.longitude;
this.lati = data.coords.latitude;
}).catch((err)=>{
console.log("Error", err);
});
let watch = this.geolocation.watchPosition(options);
watch.subscribe((data) => {
let lat_lng = data.coords.latitude+","+data.coords.longitude;
});
});
}

Ionic3 framework network.onConnect().subscribe not working?

I have created a little phone app with Ionic. I am trying to implement a bit logic where the component knows when its online or offline. To do so I am using the network plugin fom Ionic and it just does not work as expected.
instead of updating the
this.connected
value every time when I switch on / off the network, it will only do so if I switch it off / on AND do something like switching from landscape to portrait mode, or work on a different app for a while and come back to the app.
Really puzzled by that.
Here is the code:
import {Component} from '#angular/core';
import {NavController, NavParams, Platform} from 'ionic-angular';
import {GooglePlus} from '#ionic-native/google-plus';
import {SurveyService} from "./survey.service";
import {Survey} from "../../Declarations/Survey";
import {SurveyPage} from "../survey/survey";
import {Network} from "#ionic-native/network";
#Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [SurveyService, Network]
})
export class HomePage {
public surveys: Survey[] = [];
public connected;
public networkType;
constructor(public navCtrl: NavController,
private googlePlus: GooglePlus,
private surveyService: SurveyService,
public navParams: NavParams,
platform: Platform,
private network: Network) {
this.checkForNetwork();
this.surveyService.getAvailable().subscribe(surveys => {
this.checkForNetwork();
this.surveys = surveys;
})
}
login() {
this.googlePlus.login({
'webClientId': '632130231957-dmjd154jhq1eenimedri3m0de6sh7tln.apps.googleusercontent.com'
}).then((res) => {
console.log(res);
}, (err) => {
console.log(err);
});
}
logout() {
this.googlePlus.logout().then(() => {
console.log("logged out");
});
}
openSurvey = (survey: Survey) => {
this.navCtrl.push(SurveyPage, {
survey: survey
});
}
checkForNetwork = () => {
this.networkType= this.network.type;
this.network.onDisconnect().subscribe(() => {
this.connected = false;
this.network.type = null;
});
this.network.onConnect().subscribe(() => {
this.connected = 'network connected!';
setTimeout(() => {
if (this.network.type === 'wifi') {
this.connected = true;
}
}, 3000);
});
}
}
OK, I worked it out:
Turns out that ionic works perfectly fine, but I tried to change the view of my application depending on whether
this.connected
is true or false. I did not realize that I needed to tell Angular to refresh its view by using Application
applicationRef.tick();
in the right place. So basically, once the Ionic changes the value of this.connected you need to tell Angular about it, here is the corrected part of the code:
You need to inject ApplicationRef into the constructor
constructor(public navCtrl: NavController,
...
private appReference: ApplicationRef) {
...
checkForNetwork = () => {
this.networkType= this.network.type;
this.network.onDisconnect().subscribe(() => {
this.connected = false;
this.network.type = null;
this.appReference.tick();
});
this.network.onConnect().subscribe(() => {
this.connected = 'network connected!';
setTimeout(() => {
if (this.network.type === 'wifi') {
this.connected = true;
this.appReference.tick();
}
}, 3000);
});
}

Ionic 2: push notification on click

A notification appears, but upon clicking them, they only open the application again. What I want is upon clicking the notification, it opens a specific item.
In Laravel, I am using the brozot/Laravel-FCM package for Firebase Cloud Messaging (FCM) to send notifications, and on the other end, I'm using Ionic push notifications to receive and display notifications in the notification tray.
If I don't use setClickAction() on Laravel, the Ionic application opens upon clicking the notification, but if I set setClickAction(), then nothing happens. The notification merely disappears.
Laravel-code:
$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
->setSound('default')
->setClickAction('window.doSomething');
$notification = $notificationBuilder->build();
Ionic 2 framework sample:
import { Component, ViewChild } from '#angular/core';
import { Platform, Nav, MenuController, ModalController, Events, AlertController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Push, PushObject, PushOptions } from '#ionic-native/push';
import { Storage } from '#ionic/storage';
import {
SearchPage
} from '../pages/pages';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = SearchPage;
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
private menu: MenuController,
private modalCtrl: ModalController,
private events: Events,
private push: Push,
private alertCtrl: AlertController,
private storage: Storage
) {
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.
statusBar.styleDefault();
splashScreen.hide();
});
this.pushSetup();
}
pushSetup() {
const options: PushOptions = {
android: {
senderID: 'xxxxxxxxxxx',
forceShow: true
},
ios: {
senderID: 'xxxxxxxxxxx',
alert: 'true',
badge: true,
sound: 'true'
},
windows: {},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => {
});
pushObject.on('registration').subscribe((registration: any) => {
alert(registration.id);
});
pushObject.on('error').subscribe(error => alert('Error with Push plugin' + error));
}
}
(<any>window).doSomething = function () {
alert('doSomething called');
}
What am I missing?
There are these steps that need to be done for general One-Signal push notification to be implemented
Create a OneSignal Account
Add a New APP in the One Signal , configure for Android first (you can target for any platform but i'm focussing on Android as of now) .you need to get the Google Server Key and Google Project Id.
You can get the Above keys from the Firebase using this Steps
Now we are done with Configuring the OneSignal Account, now integrate with the ionic using the cordova plugin
In Ionic2 :
OneSignal.startInit(//google Server Key, //Google ProjectId);
OneSignal.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification);
OneSignal.setSubscription(true);
OneSignal.handleNotificationReceived().subscribe(() => {
// handle received here how you wish.
// this.goToReleatedPage(data.Key, data.Value);
});
OneSignal.handleNotificationOpened().subscribe((data: any) => {
//console.log('MyData'+ JSON.stringify(data.additionalData));
this.parseObject(data);
});
OneSignal.endInit();
ParsingObject in Ionic
public parseObject(obj) {
for (var key in obj) {
this.goToReleatedPage(key, obj[key]);
if (obj[key] instanceof Object) {
this.parseObject(obj[key]);
}
}
}
goToReleatedPage Method
public goToReleatedPage(Key, Value) {
//console.log("Pagename"+" " + Key + "ID" +" " + Value);
if (Key === 'xxxx') {
this.navCtrl.push(xxxPage, {
id: Value
});
} else if (Key === 'Foo') {
this.navCtrl.push(foosPage, {
id: Value,
});
} else if (Key === 'bar') {
this.navCtrl.push(barPage, {
id: Value
});
}
}
While sending the Message from OneSignal , you need to specify which page you need to open and you want to pass Id as follows