Integrating AdMob with Cocos2D-iPhone Applications

来源:互联网 发布:node实现反向代理跨域 编辑:程序博客网 时间:2024/04/30 09:07

Now updated for latest AdMob SDK that requires a UIViewController

This post provides the code needed to display AdMob ads within Cocos2D using a UIViewController.  Much of the initial content is still the same, but the code reflects the slight changes required to support the use of a UIViewController.  The updated code was tested on a 3G running IOS 4 and Cocos2D 0.99.3.

AdMob is a mobile advertising network that serves ads to be displayed on mobile devices.  Ads can be served via native applications or within a browser and are not limited to just smart phones.  AdMob offers plenty of metrics to track the quantity of served ads, geographic region, which cellphone operator, and device type.  This tutorial will provide the guidance needed to include AdMob served ads within your Cocos2D-iPhone application.   This example is based upon v.82 of the Cocos2D-iPhone framework.

Your first step is to register with AdMob to get a publisher ID and input information regarding your application.  Registration and eventual access to the SDK is free.

Once registered and logged in, you’re presented with a dashboard where you can track your applications.  As shown in the following, I already have Balloon-Boy and a mobile oriented website, moblpub.com, already registered.

Let’s add a new site by selecting the +Add Site/App button.  As shown in the following image, there are various choices available from which to publish ads.  Go ahead and select iPhone App to add the application details.

The following image shows the various details we’ll enter for the application.  Don’t worry about the iTunes link as you can come back to add it later if the application hasn’t been published yet.  You can also change the theme color, but this too can be changed later by entering your own color code values.

After selecting continue at the bottom, we can then download the SDK.  Interestingly, the SDK’s sample files will come pre-populated with a newly created publisher ID for your specific application.  We’ll get to that in a moment, but for now keep in mind that this ID will be unique for your application.  It can also be a source of frustration as I’ve seen with other users who forget to input their ID and wonder why their application isn’t serving ads.

After selecting the download SDK button and when returning to the Sites & Apps page we see the new application has been added.

Select the setup link for your application to then view the application’s details.  Again we see the particular publisher ID as well as some other features that we can control such as the types of ads we can serve.  There are many ad categories, and you could find some surprising content offered up by your site.

Selecting the Category/Type Settings tab shows the various ad categories available as well as presents an ability to turn them off.  Keep in mind that with so many devices offering up ads and a limited inventory of available ads, it’s not likely that you’ll consistently have a 100% fill rate.  Meaning, there may be just some times that an ad may not be presented due to the lack of inventory.  As a result, turning off ad categories will most likely reduce your fill rate.

Now that we have a feel for the AdMob dashboard and the various configuration capabilities, it’s  time to start integrating their SDK with our application.  Let’s untar the downloaded file and review the files.  The following image shows the provided files and sample XCode project.  Open the XCode project and take a look at the AdViewController.m file.

Upon closer inspection, we’ll see that our previously assigned Publisher ID, done at the time of the application’s creation, is pre-populated in the publisher ID string:

We’ll use this same value in a bit within our application.  The AdMob ads are displayed in 320×48 UIViews and can essentially be placed anywhere.  There are choices for other sizes, especially for the iPad, but for this exercise we’re going to stick with the smaller ads.  Once integrated, our application will display centered ads in landscape mode as shown in the following image.

The AdMob provided README within the SDK provides the necessary details for project integration.  Specifically, we start by adding the AdMob library code and headers to the XCode project. These files are contained in the AdMob subdirectory and consist of the following:

  • AdMobDelegateProtocol.h
  • AdMobView.h
  • libAdMob.a

Quite frankly, I just dragged and dropped the AdMob folder from the sample projects into my project.

We also need to ensure the following frameworks have been added to the project.

  • CoreLocation
  • CoreGraphics
  • QuartzCore
  • AddressBook
  • AudioToolbox
  • MediaPlayer

Now we’re going to add the code within the class that will display the ad.  For my particular case, I’m displaying ads in the main menu of Balloon-Boy as shown in the earlier image.

Add the following statements to the class header file that will display the ads.  In my case I added them to my MenuScene.h.

1#import "AdMobDelegateProtocol.h"
2#import "AdMobInterstitialDelegateProtocol.h"
3#import "AdMobInterstitialAd.h"
4#define AD_REFRESH_PERIOD 60.0 // display fresh ads once per minute

Then we declare the following variables within the MenuScene.h.

1AdMobView *adMobAd;
2NSTimer *refreshTimer; // timer to get fresh ads
3UIViewController *viewController;

We’ll now turn our attention to the main class file (MenuScene.m).  Include the following methods within this file where the ad will be displayed.  The provided comments are fairly self explanatory, and should give you an idea of what’s going on.

01- (void)didReceiveAd:(AdMobView *)adView {
02// put the ad at the top middle of the screen in landscape mode
03adMobAd.frame = CGRectMake(0, 432, 320, 48);
04CGAffineTransform makeLandscape = CGAffineTransformMakeRotation(M_PI * 0.5f);
05makeLandscape = CGAffineTransformTranslate(makeLandscape, -216, -134);//centers the ad in landscape mode
06adMobAd.transform = makeLandscape;
07[viewController.view addSubview:adMobAd];
08}
09 
10// Sent when an ad request failed to load an ad
11- (void)didFailToReceiveAd:(AdMobView *)adView {
12NSLog(@"AdMob: Did fail to receive ad in AdViewController");
13[adMobAd release];
14adMobAd = nil;
15}
16 
17- (void)onEnter {
18viewController = [[UIViewController alloc] init];
19viewController.view = [[CCDirector sharedDirector] openGLView];
20adMobAd = [AdMobView requestAdOfSize:ADMOB_SIZE_320x48 withDelegate:self];
21[adMobAd retain]; // this will be released when it loads (or fails to load)
22[super onEnter];
23}
24 
25- (void)onExit {
26[adMobAd removeFromSuperview];
27[adMobAd release];
28[super onExit];
29}
30 
31// Request a new ad. If a new ad is successfully loaded, it will be animated into location.
32- (void)refreshAd:(NSTimer *)timer {
33[adMobAd requestFreshAd];
34}
35 
36// AdMobDelegate methods
37- (NSString *)publisherIdForAd: (AdmobView *)adView {
38return @"a14b19f75680944"// this is your publisher ID
39}
40 
41- (UIViewController *)currentViewControllerForAd:(AdMobView *)adView {
42return viewController;
43 }
44 
45- (UIColor *)adBackgroundColor {
46return [UIColor colorWithRed:0 green:0.749 blue:1 alpha:1]; // this should be prefilled; if not, provide a UIColor
47}
48 
49- (UIColor *)primaryTextColor {
50return [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; // this should be prefilled; if not, provide a UIColor
51}
52 
53- (UIColor *)secondaryTextColor {
54return [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; // this should be prefilled; if not, provide a UIColor
55}
56 
57- (BOOL)mayAskForLocation {
58return NO; // this should be prefilled; if not, see AdMobProtocolDelegate.h for instructions
59}

If all went as planned, this newly added code should now display a rotated ad at the top middle of your view in landscape mode as shown in the following image.

As an aside, some people have experienced an error when attempting to integrate the AdMob code within their project.  The error message speaks to a duplication issue and is as follows:

ld: duplicate symbol .objc_category_name_NSCharacterSet_NSCharacterSet_Extensions in /Users/Home/Documents/Xcode/MyCrazyProject/AdMob/libAdMobDeviceNoThumb.a(NSCharacterSet_Extensions.o) and /Users/Home/Documents/Xcode/MyCrazyProject/build/Distribution-iphoneos/libcocos2d libraries.a(NSCharacterSet_Extensions.o)

Online discussion has attributed this error to both AdMob and Cocos2D referencing the same library, which in this case is TouchJSON.  As a result, some people have indicated that simply deleting TouchJSON directory from the Cocos2D package has solved the problem.  I have not experienced this error while running under v.82 of Cocos2D so can not definitively say why it shows up every once in a while.

Additionally, other users have also experienced problems when using CocosLive.  Since now they needed the TouchJSON library, they were forced to rename all of the classes in it so as to avoid conflict with AdMob.

AdMob Metrics

Now’s probably a good time to also explain some of the metrics and terms regarding online advertising.  The following image shows an example report for what was my newly released Balloon-Boy application.  Upon close inspection, you can see it shows the break down for activity by country.  As discussed earlier about available ad inventory, we can see that the application had made nearly 2,900 ad requests.  But it was fulfilled for about 2700 of them (impressions).  Out of all of those impressions there were 41 clicks.  Interestingly, the Asian market had a much higher click through rate as well as provided a much higher payout as measured by the eCPM.  The CPM acronym is derived from the latin version of the phrase “cost per mille” where “mille” in English means “thousand.”

The eCPM value is calculated by the following:

Total Earnings/Impressions * 1,000 = eCPM

The idea is to easily allow for comparison of values to see how effective a campaign is.  For us on the receiving end, it’s easy to see that the payout in Asia was much higher.  The advertisers looked to be more willing to pay more per click as well as the ads were well targeted given the high click through rate.

This concludes the Integrating AdMob with Cocos2D-iPhone Applications tutorial.  I hope that the knowledge will be useful, and feel free to contact me with any questions or comments.

trsills@pocketworx.com