A plugin that allows you to monetize your NativeScript app by integrating the Google Mobile Ads SDK into the app.
Note
Before you use this plugin, if you haven't already, setup your app for Firebase by following the instructions at @nativescript/firebase-core.
The @nativescript/firebase-admob
plugin currently supports loading and displaying the following ad types:
To install @nativescript/firebase-admob
, run the following command in the root directory of the project:
npm install @nativescript/firebase-admob
Update your Info.plist
file at App_Resources/iOS
with a GADApplicationIdentifier
key with a string value of your AdMob app ID (identified in the AdMob UI).
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy</string>
For more information about configuring the Info.plist
and setting up your App ID, see Update your Info.plist.
Add AdMob App ID (identified in the AdMob UI) to the app's AndroidManifest.xml
file, found at App_Resources/Android/src/main
. Failure to do so will result in a crash on app launch. Add the ID by adding a <meta-data>
tag with name com.google.android.gms.ads.APPLICATION_ID
, as shown below. For android:value
insert your own AdMob App ID in quotes.
<application>
<!-- Sample AdMob App ID: ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"
/>
</application>
See step 3. of Configure your app for more information about configuring AndroidManifest.xml and setting up the App ID.
To use the @nativescript/firebase-admob
plugin, follow the steps below:
Before loading ads, initialize the Mobile Ads SDK by calling the static init method on the Admob class. Call this method once, ideally right before the app boots, in the main.ts
file.
import { Admob } from '@nativescript/firebase-admob'
Admob.init()
The Mobile Ads SDK is now imported and you're ready to implement an ad. Click any of the links below to get detailed implementation steps for your desired ad format.
Banner ads are rectangular ads that appear at the top or bottom of the device screen. They stay on screen while users are interacting with the app, and can refresh automatically after a certain period. If you're new to mobile advertising, they're a great place to start.
Note
When developing your app, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account. Make sure you replace the test unit ID with your ad unit ID before publishing your app.
To enable dedicated test ad unit ID for banners, visit the links below:
Below are examples of adding a Banner ad in several NativeScript flavors.
Register the plugin namespace in the Page element under a prefix(ui
for example), access the BannerAd
view from the namespace via the prefix and add it to your XML.
The BannerAd
requires the following attributes to be set:
unitId
BannerAdSize
: You can set this value in the callback function of the layoutChanged
event. For more information, see Customize the banner ad sizeheight
and width
<Page xmlns:ui="@nativescript/firebase-admob">
<StackLayout>
<ui:BannerAd
height="100"
width="100"
unitId="{{bannerAdUnit}}"
layoutChanged="{{loadBanner}}"
/>
</StackLayout>
<!-- ... -->
</Page>
import { BannerAdSize } from '@nativescript/firebase-admob'
export function loadBanner(args) {
const banner = args.object
banner.size = new BannerAdSize(100, 100)
banner.load()
}
Register the BannerAd
view by adding its AdmobModule
to the imports
array of the @NgModule
decorator of the component where you want to use the view.
import { AdmobModule } from '@nativescript/firebase-admob/angular';
@NgModule({
imports: [
AdmobModule
],
declarations: [
AppComponent
],
bootstrap: [AppComponent]
})
Next, add the BannerAd
view to HTML. The BannerAd
requires the following attributes to be set:
unitId
BannerAdSize
: You can set this value in the callback function of the layoutChanged
event. For more information, see Customize the banner ad sizeheight
and width
<BannerAd
height="100"
width="100"
[unitId]="bannerAdUnit"
(layoutChanged)="bannerLoaded($event)"
>
</BannerAd>
Register the BannerAd
view in the app.ts
file as follows:
import { createApp } from 'nativescript-vue'
import Admob from '@nativescript/firebase-admob/vue'
import Home from './components/Home.vue'
const app = createApp(Home)
app.use(Admob)
And then add it to markup as follows. The BannerAd
requires the following attributes to be set:
unitId
BannerAdSize
: You can set this value in the callback function of the layoutChanged
event. For more information, see Customize the banner ad sizeheight
and width
<BannerAd
height="100"
width="100"
:unitId="bannerAdUnit"
@layoutChanged="bannerLoaded"
/>
To define a custom banner size, you have 2 options:
BannerAdSize
class with the desired width and height and set it to the size
attribute of BannerAd
.import { BannerAdSize } from '@nativescript/firebase-admob'
banner.size = new BannerAdSize(300, 50)
size
to any of the constants of the BannerAdSize
class.The table below lists the available constants and the sizes they represent.
AdSize Constant | Size in dp (WxH) | Description |
---|---|---|
BANNER | 320x50 | Standard Banner |
LARGE_BANNER | 320x100 | Large Banner |
MEDIUM_RECTANGLE | 320x250 | Medium Rectangle |
FULL_BANNER | 468x60 | Full-Size Banner |
LEADERBOARD | 728x90 | Leaderboard |
createAnchoredAdaptiveBanner(width, orientation) | Provided width x Adaptive height | Adaptive Banner |
createInLineAdaptiveBanner(width, orientation) | Provided width x Adaptive height | Adaptive Banner |
The plugin enables you to listen to different lifecycle events of an ad, such as when an ad is loaded. Register the events handlers before calling the load
method.
const bannerView = event.object
// Called when an ad is successfully received.
bannerView.on('adLoaded', args => {
console.log('Ad loaded.')
})
// Called when an ad request failed.
bannerView.on('adFailedToLoad', args => {
console.log('Ad failed to load: ', args.error)
})
// Called when the user removes an overlay that covers the screen.
bannerView.on('adClosed', args => {
console.log('Ad closed.')
})
// Called when an impression occurs on the ad.
bannerView.on('adImpression', args => {
console.log('Ad impression.')
})
// Called when an tap/touch/click occurs on the ad.
bannerView.on('adClicked', args => {
console.log('Ad tapped')
})
To display a banner ad to the user, get the reference to the BannerAd
view and call the load
method on it.
bannerView.load()
Interstitial ads are full-screen ads that cover the interface of an app until closed by the user. They're best used at natural pauses in the flow of an app's execution, such as between levels of a game or just after a task is completed.
Note
When your app is in development mode, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account. Make sure you replace the test unit ID with your ad unit ID before publishing your app. To enable dedicated test ad unit ID, visit the links below:
To display an Interstitial ad to the user, follow the steps below:
InterstitialAd
class from @nativescript/firebase-admob
.import { InterstitialAd } from '@nativescript/firebase-admob'
Create an Interstitial ad instance by calling the static createForAdRequest
on the class. The createForAdRequest
method requires an adUnitId and you can optionally pass a RequestOptions object.
import { InterstitialAd } from '@nativescript/firebase-admob'
const ad = InterstitialAd.createForAdRequest('ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy')
To listen for the ad lifecycle events, such as when the ad is display or dismissed, call the onAdEvent
method on the ad instance, before displaying the ad, passing it a callback function to handle the events.
import { InterstitialAd } from '@nativescript/firebase-admob'
const ad = InterstitialAd.createForAdRequest('ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy')
ad.onAdEvent((event, error, data) => {
switch (event) {
case AdEventType.LOADED:
break
case AdEventType.CLOSED:
break
case AdEventType.OPENED:
break
case AdEventType.IMPRESSION:
break
case AdEventType.FAILED_TO_SHOW_FULL_SCREEN_CONTENT:
break
}
})
load
method on the ad instance.import { InterstitialAd } from '@nativescript/firebase-admob'
const ad = InterstitialAd.createForAdRequest('ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy')
ad.onAdEvent((event, error, data) => {
switch (event) {
case AdEventType.LOADED:
break
case AdEventType.CLOSED:
break
case AdEventType.OPENED:
break
case AdEventType.IMPRESSION:
break
case AdEventType.FAILED_TO_SHOW_FULL_SCREEN_CONTENT:
break
}
})
ad.load()
To display the ad, call the show
method on the ad instance. This method is called after the load
method.
import { InterstitialAd } from '@nativescript/firebase-admob'
const ad = InterstitialAd.createForAdRequest('ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy')
ad.onAdEvent((event, error, data) => {
switch (event) {
case AdEventType.LOADED:
break
case AdEventType.CLOSED:
ad.show()
break
case AdEventType.OPENED:
break
case AdEventType.IMPRESSION:
break
case AdEventType.FAILED_TO_SHOW_FULL_SCREEN_CONTENT:
break
}
})
ad.load()
Native ads are ad assets that are presented to users via UI components that are native to the platform. They're shown using the same types of views with which you're already building your layouts, and can be formatted to match the visual design of the user experience in which they live. In coding terms, this means that when a native ad loads, your app receives a NativeAd object that contains its assets, and the app (rather than the Google Mobile Ads SDK) is then responsible for displaying them.
To add a Native ad to your {N} Core app, follow these steps:
ui
(this can be any name), with the Page element.<Page xmlns:ui="@nativescript/firebase-admob">
NativeAdView
and add it to markup.<Page xmlns:ui="@nativescript/firebase-admob">
<ActionBar title="Admob" />
<StackLayout>
<ui:NativeAdView height="400" loaded="{{nativeAdLoaded}}" />
</StackLayout>
</Page>
Note
When developing your app, make sure you use test ad unit IDs rather than live, production ads. Failure to do so can lead to suspension of your account. Just make sure you replace the test ad unit ID with your own ad unit ID before publishing your app.
To enable dedicated test ad unit ID, visit the links below:
NativeAdLoader
class from @nativescript/firebase-admob
in the view model file.import { NativeAdLoader } from '@nativescript/firebase-admob'
The NativeAdLoader
class is an interface for managing the the Native ad.
NativeAdLoader
. Create an instance of NativeAdLoader
by calling its constructor function. The constructor function accepts 3 parameters. The required adUnitId as the first parameter, optional RequestOptions and NativeAdOptions objects as the second and third parameter, respectively.const loader = new NativeAdLoader('ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy', null, {
nativeAdOptions: {
adChoicesPlacement: AdChoicesPlacement.TOP_RIGHT
}
})
To listen to the Native ad lifecycle events, call the onAdEvent
method on the NativeAdLoader
instance when the NativeAdView
has loaded.
<ui:NativeAdView height="400" loaded="{{ nativeAdLoaded }}">
<GridLayout height="300" width="300">
<Label id="headLineView" />
<ui:MediaView id="mediaView" height="100%" />
<Label id="bodyView" />
<Button id="callToActionView" />
</GridLayout>
</ui:NativeAdView>
function nativeAdLoaded(event) {
const view = event.object
loader.onAdEvent((event, error, data) => {
if (event === NativeAdEventType.LOADED) {
const ad = data as NativeAd
const headLineView = view.getViewById('headLineView')
headLineView.text = ad.headline
const mediaView = view.getViewById('mediaView')
view.mediaView = mediaView
mediaView.mediaContent = ad.mediaContent
const callToActionButton = view.getViewById('callToActionView')
view.callToActionView = callToActionButton
callToActionButton.text = ad.callToAction
const bodyView = view.getViewById('bodyView')
bodyView.text = ad.body
view.nativeAd = ad
console.log('nativead loaded')
} else if (event === 'adFailedToLoad') {
console.log('nativead failed to load', error)
}
})
}
load
method on a NativeAdLoader instance.loader.load()
A NativeAdOptions object is used to set the following options on the native ad.
Property | Type | Description |
---|---|---|
returnUrlsForImageAssets | boolean | Optional: If set to true , the SDK will not load image asset content and native ad image URLs can be used to fetch content. Defaults to false . |
multipleImages | boolean | Optional: Some image assets contain a series of images. Setting this property to true tells the app to display all the images of an asset. The false (the default) value informs the app to display the first image from the series of images in an image asset. |
adChoicesPlacement | AdChoicesPlacement | Optional: The AdChoices overlay is set to the top right corner by default. Apps can change which corner this overlay is rendered in by setting this property to one of the following: |
videoOptions | videoOptions | Optional: Used to set video options for video assets returned as part of a native ad. If an ad contains a video(if ad.mediaContent.hasVideoContent = true ), display the video. |
mediaAspectRatio | MediaAspectRatio | Optional: This sets the aspect ratio for image or video to be returned for the native ad. |
enum AdChoicesPlacement {
TOP_LEFT = 'topLeft',
TOP_RIGHT = 'topRight',
BOTTOM_RIGHT = 'bottomRight',
BOTTOM_LEFT = 'bottomLeft'
}
The videoOptions
property is an object with the following properties:
Property | Type | Optional |
---|---|---|
startMuted | boolean | Yes |
clickToExpandRequested | boolean | Yes |
customControlsRequested | boolean | Yes |
enum MediaAspectRatio {
LANDSCAPE = 'landscape',
PORTRAIT = 'portrait',
SQUARE = 'square',
ANY = 'any'
}
That's it! Your app is now ready to display native ads.
Rewarded ads are ads that users have the option of interacting with in exchange for in-app rewards.
Note
When developing your app, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account. Make sure you replace the test unit ID with your ad unit ID before publishing your app.
To enable dedicated test ad unit ID, visit the links below:
Follow these steps to display a Rewarded ad:
RewardedAd
class from @nativescript/firebase-admob
.import { RewardedAd } from '@nativescript/firebase-admob'
RewardedAd
instanceCreate a Rewarded ad instance by calling the createForAdRequest
static method on the RewardedAd
class and passing it the ad unit id.
import { RewardedAd } from '@nativescript/firebase-admob'
const ad = RewardedAd.createForAdRequest('ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy')
load
method to load the ad, call the onAdEvent
method passing it a callback function to handle the ad events.import { RewardedAd } from '@nativescript/firebase-admob'
const ad = RewardedAd.createForAdRequest('ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy')
ad.onAdEvent((event, error, data) => {
if (event === AdEventType.LOADED) {
console.log('rewarded', 'loaded')
} else if (event === AdEventType.FAILED_TO_LOAD_EVENT) {
console.error('loading error', error)
}
})
load
method on the RewardAd
instance.import { RewardedAd } from '@nativescript/firebase-admob'
const ad = RewardedAd.createForAdRequest('ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy')
ad.onAdEvent((event, error, data) => {
if (event === AdEventType.LOADED) {
console.log('rewarded', 'loaded')
} else if (event === AdEventType.FAILED_TO_LOAD_EVENT) {
console.error('loading error', error)
}
})
ad.load()
To show the ad on the screen, call the show()
method on the ad instance.
import { RewardedAd } from '@nativescript/firebase-admob'
const ad = RewardedAd.createForAdRequest('ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy')
ad.onAdEvent((event, error, data) => {
if (event === AdEventType.LOADED) {
console.log('rewarded', 'loaded')
ad.show()
} else if (event === AdEventType.FAILED_TO_LOAD_EVENT) {
console.error('loading error', error)
}
})
ad.load()
RewardAd emits the following lifecycle events that you can listen to:
ad.onAdEvent((event, error, data) => {
switch (event) {
case AdEventType.LOADED:
break
case AdEventType.CLOSED:
break
case AdEventType.OPENED:
break
case AdEventType.IMPRESSION:
break
case AdEventType.FAILED_TO_SHOW_FULL_SCREEN_CONTENT:
break
}
})
onAdEvent
with the event rewarded_earned_reward
'is invoked when the user earns a reward. Be sure to implement this and reward the user for watching an ad.
The RequestConfiguration object collects the global configuration for every ad request and is applied by firebase().admob().setRequestConfiguration()
.
For child-directed ads setting, read Child-directed setting.
The following example indicates that you want your content treated as child-directed for purposes of COPPA:
import { Admob, RequestConfiguration } from '@nativescript/firebase-admob'
const requestConfiguration: RequestConfiguration = {
tagForChildDirectedTreatment: true
}
Admob.getInstance().requestConfiguration = requestConfiguration
To handle ads requests for users under the age of consent, read Users under the age of consent.
The following example indicates that you want TFUA included in your ad request.
import { Admob, RequestConfiguration } from '@nativescript/firebase-admob'
const requestConfiguration: RequestConfiguration = {
tagForUnderAgeOfConsent: true
}
Admob.getInstance().requestConfiguration = requestConfiguration
If the tags to enable the Child-directed setting and tagForUnderAgeOfConsent
are both set to true
, the child-directed setting takes precedence.
This setting can be set via RequestConfiguration.maxAdContentRating
:
AdMob ads returned for these requests have a content rating at or below that level. The possible values for this network extra are based on digital content label classifications, and should be one of the following MaxAdContentRating objects:
The following code configures a RequestConfiguration
object to specify that an ad content returned should correspond to a digital content label designation no higher than G:
import {
Admob,
MaxAdContentRating,
RequestConfiguration
} from '@nativescript/firebase-admob'
const requestConfiguration: RequestConfiguration = {
maxAdContentRating: MaxAdContentRating.G
}
Admob.getInstance().requestConfiguration = requestConfiguration
Apache License Version 2.0