react-native-firebase/lib/modules/admob/Interstitial.js

120 lines
2.7 KiB
JavaScript
Raw Normal View History

2018-01-31 16:05:38 +00:00
import { Platform } from 'react-native';
import { statics } from './';
import AdRequest from './AdRequest';
import { SharedEventEmitter } from '../../utils/events';
2018-01-31 16:05:38 +00:00
import { getNativeModule } from '../../utils/native';
import { nativeToJSError } from '../../utils';
2018-01-31 16:05:38 +00:00
import type AdMob from './';
let subscriptions = [];
export default class Interstitial {
2018-01-31 16:05:38 +00:00
_admob: AdMob;
constructor(admob: AdMob, adUnit: string) {
// Interstitials on iOS require a new instance each time
if (Platform.OS === 'ios') {
2018-01-31 16:05:38 +00:00
getNativeModule(admob).clearInterstitial(adUnit);
}
for (let i = 0, len = subscriptions.length; i < len; i++) {
subscriptions[i].remove();
}
subscriptions = [];
2018-01-31 16:05:38 +00:00
this._admob = admob;
this.adUnit = adUnit;
this.loaded = false;
SharedEventEmitter.removeAllListeners(`interstitial_${adUnit}`);
2018-01-25 18:25:39 +00:00
SharedEventEmitter.addListener(
`interstitial_${adUnit}`,
this._onInterstitialEvent
);
}
/**
* Handle a JS emit event
* @param event
* @private
*/
2018-01-25 18:25:39 +00:00
_onInterstitialEvent = event => {
const eventType = `interstitial:${this.adUnit}:${event.type}`;
let emitData = Object.assign({}, event);
switch (event.type) {
case 'onAdLoaded':
this.loaded = true;
break;
case 'onAdFailedToLoad':
emitData = nativeToJSError(event.payload.code, event.payload.message);
emitData.type = event.type;
break;
default:
}
SharedEventEmitter.emit(eventType, emitData);
SharedEventEmitter.emit(`interstitial:${this.adUnit}:*`, emitData);
};
/**
* Load an ad with an instance of AdRequest
* @param request
* @returns {*}
*/
loadAd(request?: AdRequest) {
let adRequest = request;
if (!adRequest || !Object.keys(adRequest)) {
adRequest = new AdRequest().addTestDevice().build();
}
2018-01-31 16:05:38 +00:00
return getNativeModule(this._admob).interstitialLoadAd(
this.adUnit,
adRequest
);
}
/**
* Return a local instance of isLoaded
* @returns {boolean}
*/
isLoaded() {
return this.loaded;
}
/**
* Show the advert - will only show if loaded
* @returns {*}
*/
show() {
if (this.loaded) {
2018-01-31 16:05:38 +00:00
getNativeModule(this._admob).interstitialShowAd(this.adUnit);
}
}
/**
* Listen to an Ad event
* @param eventType
* @param listenerCb
* @returns {null}
*/
on(eventType, listenerCb) {
if (!statics.EventTypes[eventType]) {
2018-01-25 18:25:39 +00:00
console.warn(
`Invalid event type provided, must be one of: ${Object.keys(
statics.EventTypes
).join(', ')}`
);
return null;
}
2018-01-25 18:25:39 +00:00
const sub = SharedEventEmitter.addListener(
`interstitial:${this.adUnit}:${eventType}`,
listenerCb
);
subscriptions.push(sub);
return sub;
}
}