How I Finally Got AdMob and Ionic Framework to Play Nice Together

Note: Some of the plugins referenced in this article have had their names, and possibly their APIs, changed. The information contained herein may no longer work. Please don't rely on it until I have had a chance to review and update it. -Mike Callaghan

TLDR

This is a summary of how to display ads in my MDCL (1650) mobile application, which was written using the Ionic FrameworkIf you want to see the sample project that displays both banner and interstitial ads, you can look at my AdMob Demo app on GitHub.

AdMob


The first thing that's necessary is to get an AdMob account, which you can create at https://www.google.com/admob/

Ionic Starter App


If you don't already have an ionic app, you can create one with the following command, which will create a folder named myApp in your current folder, and initialize it with an empty application.

ionic start myApp blank



ngCordova


Next, you'll need to install the ngCordova bower package and include that in your project. This script does most of the heaving lifting of wrapping more than 60 Cordova plugins inside of Angular services, making them easier to reference from your Ionic applications. You can do that with this command:

bower install ngCordova --save

Angular Module

Next, we need to make sure that the Angular module that makes up your app is fully aware of the new module, by adding it as a dependency. Open up www/js/app.js and find the angular module declaration. It will look something like this: 

Modify it to look like this instead:


 

Controller, Route, and View

While you're in there, you may as well set up a default route, a controller, and a simple view. I went ahead and refactored the inline function into a named function called startup, but otherwise left it unchanged. Then I added a controller and a config function. My complete module definition now looks like this;




I put my one route in the config function, as shown here:




And finally, my HomeController, where all of the magic happens. Unfortunately, it's too large to show all at once, so I'll present it bite-sized chunks and explain as I go.




You will notice that  I named the controller "HomeController," which is how I referred to it in the controller definition and to the $stateProvider. I am also injecting the $cordovaGoogleAds service from ngCordova.

At the top of the function, I use a pattern borrowed from John Papa. The controller's this variable is saved as a local object called vm, and then every public property I want to expose in the view will be created as a property on this vm object. As an aside, vm stands for "view model," which is from the Model-View-ViewModel pattern popularized in WPF and Silverlight, and still useful in Angular. 

Next, I create a local variable to hold my AdMob Unit Id, one for banner ads and one for the interstitial (full-page) ads. I have removed my actual unit IDs. You'll want to replace those values with your own.




Next, I create a  listener for cordova 'deviceread' event. If you don't do this, your controller will probably execute before cordova is finished initializing, and then nothing will work. 




The call to $scope.$apply() is only necessary to update the view with the text for vm.adSupport. Because the event fires outside of Angular's normal digest cycle, Angular doesn't know the value has changed. 

Now let's look at the setupAds function that was referenced above.


   

Here I am calling into the ngCordova wrapper to create a banner ad. This function takes a single parameter, which is an options object. There are a lot more options, but this is about the smallest set you can send. We pass the AdMob Unit ID, tell it where to display, and to display it automatically. 

Take a close look at the position attribute. This reveals an interesting fact about ngCordova. Even though the plugin is wrapped in an Angular factory, it is still accessible on the $window object. This comes in handy in this case, because the ngCordova wrapper does not expose the AD_POSITION.BOTTOM_CENTER constant. 


The next code block prepares, but does not automatically show, a full-page ad. I prepare it now so that it will be available when it is needed later, such as on a button click, a page transition, or any other convenient time. 



Finally, this next function is attached to vm.showFullAd, which I will be attaching to a button on my view later. 





One oddity I noticed is that once the ad is shown, it won't show again unless it prepared again. So I prepare a new one immediately after I show the first one. It's a bit of code duplication, but hey, this is a demo. 

HTML

Now it's time to wire the controller to the view.

index.html  

First, we need to make sure the ngCordova script is loaded with the rest of our application. Open up www/index.html and find the line that reads:





Now edit it to look like this:






It's worth opening that file and reviewing its contents. You'll notice that each plugin is implemented as an Angular factory. Also notice the two comments that preceed each one. The first is the command that will install the plugin, and the other is a link to its source on github.com. I learned the hard way that just having ngCordova doesn't actually accomplish anything unless you install the plugin first. In retrospect, this makes sense and is even somewhat obvious. ngCordova doesn't include the plugins, but simply provides a convenient abstraction over them, assuming they exist.

In the case of AdMob, there are actually two of them in the script. I wrestled with the first one for awhile, $cordovaAdMob, before giving up and trying the second one, $cordovaGoogleAds. That one is based on a different plugin, and I found it much simpler to use, although it appears to be a little incomplete, as I alluded to earlier with the lack of some common options constants.

Finally, replace the entire HTML body with this:




Ionic will put your view's content inside the <ion-nav-viewtag. We'll create that content next.

home.html

Remember way back when I created the route in the $stateProvider? I also provided the name of a view, an HTML fragment that I put in www/templates/home.html. If you are following along, you'll want to create that folder and file now. Delete all of the default HTML and enter this instead.




The first line sets the page title. The tag tells Ionic where our content is defined. Inside of that I have a few tags to make things look nice. The real meat is the tag that displays a controller variable indicating whether or not ad support was successfully initialized, and the button that can be clicked to display a full-page ad. The button is wired to my showFullAd function on the controller, and is only enabled if the adSupport is truthy.

Now let's wrap everything up and see it in action.

AdMob Plugin

I mentioned earlier that ngCordova still requires the plugin to be installed. Let's do that now. However, instead of using the cordova command, I'm going to use the ionic command. The difference is that the ionic command will also update my package.json file. Ionic has a command to restore your plugins from the package.json file, which comes in handy if you ever want someone else to build your app from source control. You don't want to store your plugins in source control.




ionic plugin add com.google.cordova.admob


To restore the plugins later if the plugins folder gets deleted, you can run the following two commands:
ionic state restore
ionic platform add

Let's See it!

Finally, it's time to see your handiwork. If you followed along, and neither of us made any mistakes, simply run this command, stand back, and watch.
ionic emulate ios
or
ionic run android

Use whichever one makes sense for your own environment. I don't recommend using the android emulator, because the emulator is so slow, and running on a real device is so simple. With iOS, the opposite is true.

If all went well, your page should look like this, with Google's AdMob test banner ad shown at the bottom of the screen. 



Click the button to display a full-page ad. 



Wrapping Up


Getting the AdMob ads to display in my app wasn't as easy as I'd hoped, but it's working now. If you know of a better, easier way, please feel free to comment here. I'm also eager to accept pull requests on my sample github project.



Hopefully, the explanation here and sample app will help someone else avoid some of the struggles I faced. 


Comments

  1. Hi, you article is actually help me lots :)
    i have beens struggle for few days just to get the admob working on my little apps.

    but, i got another issue, if i only want to show the admob on specific view, do you have any idea for that?
    Thanks

    ReplyDelete
    Replies
    1. Only call the admob code from the controller for that particular view.

      Delete
    2. Hi, How can I show the ad banner or the ad Interstitial on particular pages?

      I would like to only show them on 3 pages in my ionic app.

      Kind regards.

      Delete

Post a Comment

Popular posts from this blog

How to copy your Frozen Free Fall progress to a new phone

Ionic vs. Bootstrap - for a Web App