您的位置:首页 > 移动开发 > Cocos引擎

How to Integrate AdWhirl into a Cocos2D Game

2012-05-17 09:13 666 查看


How to Integrate AdWhirl into a Cocos2D Game

If you're new here, you may want to subscribe to my RSS
feed or follow me on Twitter.
Thanks for visiting!

This is a blog post by iOS Tutorial Team member Ibrahim
Kteish, a student inspired by the iPhone with a passion for creating iOS software, and the cofounder of istockplus.com.





Learn how to get a high fill rate with ads in your game with AdWhirl!

If you want to make an ad-based game, your first thought might be “well, I’ll just enable iAd!” Although iAd is a great ad network (and definitely easy to integrate, since it’s built into iOS), if you try it out in practice you’ll notice very low fill rates.

This means that often when you want to display an ad, there won’t be an ad available, and so you’ll get less money than you potentially might have otherwise. And since the goal is to make money, obviously this isn’t ideal!

This is where an ad mediation framework like AdWhirl comes to the rescue – and that’s the focus of this tutorial!

AdWhirl is a free, open source tool that allows developers to serve ads from any number of Ad networks you have accounts on, as well as your own house ads (to run your own ad campaigns and cross-promote your apps), via one simple client SDK.

By utilizing multiple ad networks and Switch ad networks on the fly, you can select which ones perform best for your app and ensure you have a high fill rate. Note AdWhirl won’t “mediate” your payments, the payments will be made by each network you’ve signed
on.

In this tutorial, we will show you step-by-step how to get started with AdWhirl, and integrate it into one of the Cocos2D tutorials from this site. If you follow along, you’ll be all set up with AdWhirl and ready to integrate it into your own apps or games!


AdWhirl: An Overview

The way AdWhirl works is you configure a number of ad networks which you want to serve ads, and AdWhirl chooses one to serve an ad for you, based on your preferences and ad availability.

To configure AdWhirl to use an ad network, you have to create an account on that network. You also have to integrate that ad network’s SDK into your project.

AdWhirl supports a huge array of ad networks (currently 17 at the time of writing this article!), and we could set up AdWhirl to use all 17 networks, but then this tutorial would take forever!

So for the purposes of this tutorial, we are just going to configure AdWhirl to use two ad networks:

iAd.
iAd is Apple’s built-in advertising solution. You might have read about it already in our How
To Integrate iAd into your iPhone App tutorial. iAd is great, but its fill rate is often low. So when it’s not available, AdWhirl can help with that by serving ads from another provider such as AdMob.

AdMob.
AdMob is one of the world’s largest mobile advertising platforms and claims to serve more than 40 billion mobile banner and text ads per month across mobile Web sites and handset applications. Their rates are generally not as high as iAd, but they have more
ads available.

Before we do anything with AdWhirl, we need to enable iAds for our app, and set up an AdMob account. So let’s get started!


Enabling iAds for your App

In order to receive iAds in your app, you need to enable the iAd service for your app in iTunes Connect via the following steps:

Log onto the iOS
Developer Center, go to the iOS Provisioning Portal, and create a new App ID for your app. We’re going to be integrating AdWhirl into a space game in this tutorial, so you might want to name it something like “com.yourdomain.spacegame.”

Log onto iTunes
Connect and create a new app, choosing the App ID you just created. Just enter placeholder information for now until you get to the “waiting for upload” stage. Don’t worry you can change all this info later, we just have to create an enter to make iTunes
Connect happy for now.

Once you’ve created your app’s entry, open it up in iTunes Connect and click “Set Up iAd Network”, as shown below:





Finally you must specify whether your audience is under 17 years of age, as shown in the following screenshot. This helps target your ads more appropriately for your age group.





Click the Enable iAds button and Save. The only other thing you have to do is go to the Contracts & Banking module in iTunes Connect, and accept the iAd network agreement if you haven’t already.


Creating an AdMob Account

Next, we will create an account for the AdMob network. Go ahead and visit the admob.com and
click on Get Started:





Second, follow the steps to create an account by filling in the info and accepting the terms of service. When you’re done you should see a page like this:





Next, we need to create a new app in order to get a Publisher
ID
that we need for AdWhirl.

To do this, click on the Sites & Apps tab, and select the Add Site/App button from the dropdown. It will prompt you to enter your payment details, as you can see in the screenshot below:





Once you’ve entered your payment details, choose iPhone app from the next page:





A dropdown will appear to allow you to enter some additional information on your app. Enter the information as shown below, and then click continue:





You will then arrive at a screen where you can download the AdMob SDK. Be sure to download this, because you’ll need the SDK later on in this tutorial.

Now we just need to get the Publisher ID for the new app we created. To do this, click the “Go to Sites/Apps” button, scroll down to your new Space Game entry, move your mouse over it so the “Manage Settings” button appears, and click that button.





Finally, you will see your Publisher ID toward the top of this information sheet! Copy this down, as you will need it later in this tutorial.





Creating an AdWhirl Account

It’s easy to get started with AdWhirl. Simply visit adwhirl.com and
click the “Sign Up Now” button:





You’re then presented with a sign up page. Simply fill in the text fields with your data, enter the captcha, and select the checkbox, as shown below:





Once you’ve clicked register you will get a message saying to check your email as shown in the next screenshot:





Go ahead and find the email sent to you, click the link, and you will get a confirmation message as shown below:





Click log in, and fill in the dialog boxes to log into your new account. You’ll arrive at a page where you can add and track your applications:





Congrats, you now have an AdWhirl account! Let’s go ahead and an app next.


Adding an App

From the Apps tab, you can see all of the apps that you’ve integrated with AdWhirl.

Click the Add Application button to add a new app, as shown in the next screenshot:





You’ll then be presented with the following page:





Enter the name and App Store URL of your app (if your app isn’t released yet, you can leave the URL field blank), and choose iPhone for the Platform field.

Optionally, you can set additional preferences of how ads should display in this app:

Refresh
Rate
: determines how many seconds before a new ad appears.

Transition
Animation
: describes how to execute an animation from the old state to the new state over time.

Allow
Location Access
: if this is on, will ask allow AdWhirl to attempt to get location data for the user. The problem is this will cause a popup to the user asking if it’s OK for the app to get their location, and if the app doesn’t need it this
will be suspicious and annoying to the user.

For this tutorial, let’s leave all of those options at the default settings. Click Add App, and your app will be created in the AdWhirl system (you might have to refresh the page):





Click on the app name that you just created, and you’ll see the app’s SDK key listed to the right of its name:





This key is quite important – you’ll be pasting this into the SDK code to identify your app to AdWhirl’s servers.


Configuring Ad Networks

The next step is to configure the parameters for each ad network that you want to serve ads to your app. In this tutorial, we’re just going to configure the AdMob and iAd accounts we set up, but you can enable more ad networks if you want in your own apps!

Let’s start by setting up AdMob. Find the AdMob entry, click the Configure button next to it, and you’ll be prompted to enter your AdMob publisher ID. Enter the Publisher ID you get from earlier in the tutorial:





Next find the iAd entry, click the Configure button next to it, and you’ll be prompted to enter your Apple ID. Enter your Apple ID to continue:





Once you’ve done this, you can turn the network on or off using the On-Off button, and choose the percent of traffic that you want to assign to each network as the next screenshot shown (AdMob On iAd Off).





The way this works is AdWhirl chooses an ad network based on the traffic allocation percentages you’ve applied. When it’s time to serve an add, these allocation percentages tell AdWhirl where to send ad requests on the first attempt. If an ad request fails,
AdWhirl will try another network according to the backfill priorities you set (which we’ll configure in a minute), one after another until an ad is found or the list is exhausted.

Note that even if a network has a 0% allocation, it may still get some requests through backfill. To ensure that no ad requests ever go to a network, make sure to switch it off using the On-Off button.





Note that your allocation percentages must add up to 100% before you’ll be able to save these settings as next screenshot shown.





As always when you are done with Ad Network Settings, click on Save changes.

Last but not least, go to Backfill priority as shown in the screenshot below – you’ll use this page to tell AdWhirl what priorities to follow in case an initial ad request is unfilled by one of your networks. AdWhirl uses low numbers to represent high priority:





Creating House Ads

House Ads (formerly known as custom ads) are ads of your own creation that you display in your apps. You can use these to cross-promote your other apps, apps of your friends, or anything else you might want to use them for.

To create a House Ad in your AdWhirl account, click the House Ads tab along the top of the screen App as shown in the next screenshot.





Click the “Add House Ad” button and the next screenshot appears:





Fill in the information as you desire. After creating your ad, be sure to go back to your Ad Network Settings screen, turn on House Ads, and edit the traffic percentages and backfill priority as you would like.


Integrating the AdWhirl SDK

At this point, you should have the AdMob SDK (if you don’t, you can get it by clicking “Get Publisher Code” from your Space Game app settings in AdMob, or download
it here).

But you haven’t downloaded the AdWhirl SDK yet, so go ahead and download
it now. Obviously choose the iPhone SDK, as shown below:





We’re going to integrate AdWhirl into one of the tutorials from this site – specifically the game from theSpace
Shooter tutorial. If you purchased the Space
Game Starter Kit you will be particularly happy we chose this game to base it on, since it will be really easy apply this tutorial to the Starter Kit! :]

So go ahead and download the space
game from the tutorial. Unzip and run it in Xcode and make sure everything is working properly. Note that this game requires the accelerometer, so you might want to try it on your device if you want to play.

Next, go ahead and unzip the AdWhirl SDK. Once you unzip the file, drag only the AdWhirl subfolder into the group in your project. Verify that “Copy items into destination group’s folder (if needed)” is checked, and click Add as shown in the next screenshot.





Once you’ve added the AdWhirl folder to your project Add the following frameworks as shown in the next screenshot:

AddressBook.framework

CoreLocation.framework

MapKit.framework (weak-linked for OS 2.X support)

MediaPlayer.framework

MessageUI.framework (weak-linked for OS 2.X support)

SystemConfiguration.framework

iAd.framework (required for iAd, weak-linked for OS 3.X support)

libsqlite3.dylib

libz.dylib





The final step is to remove the adapters in AdWhirl/adapters that we don’t need. Open that folder and remove all of the files except for the ones we need (iAd, AdMobs, and AdNetworkAdapter), as shown below:





Now that we have the AdWhirl SDK brought into your project, let’s bring in the AdMob SDK. Unzip the file, and drag the GoogleAdMobAdsSDK folder into the space game project. Make sure “Copy items into destination group’s folder (if needed)” is selected, and
click Finish, as shown in the next screenshot:





Compile and run your project on your device to make sure everything works so far, and finally let’s start coding!

Using
the AdWhirl SDK


Open HelloWorldLayer.h and make the following modifications:

// Add to top of file
#import "AdWhirlView.h"
#import "AdWhirlDelegateProtocol.h"
#import "AppDelegate.h"
#import "RootViewController.h"

enum GameStatePP {
kGameStatePlaying,
kGameStatePaused
};

// Mark class as implementing AdWhirlDelegate
@interface HelloWorldLayer : CCLayer <AdWhirlDelegate>

// Add inside @interface
RootViewController *viewController;
AdWhirlView *adWhirlView;

enum GameStatePP _state;

// Add after @interface
@property(nonatomic,retain) AdWhirlView *adWhirlView;
@property(nonatomic) enum GameStatePP state;

Here we import the header files we need for AdWhirl, and the AppDelegate and RootViewController (since we’ll be adding a view to the view controller to display the ad view).

Then we create an enumeration called GameStatePP to keep track of the two different game states we’re going to have – playing or paused.

We also mark the class as implementing AdWhirlDelegate, and create some instance variables and properties.

Next, switch to HelloWorldLayer.m and make the following modifications:

// Add after @implementation
@synthesize state = _state, adWhirlView;

// Add at end of init
self.state = kGameStatePlaying;

// Add in dealloc
self.adWhirlView.delegate = nil;
self.adWhirlView = nil;

This is just the basic setup code to synthesize our properties, initialize the game state, and cleanup in dealloc. Time to move onto the fun stuff!

Implementing
AdWhirlDelegate


Now we will implement the Adwirl Delegate methods. Go to the end of HelloWorldLayer.m and the following 2 methods before the @end :

- (void)adWhirlWillPresentFullScreenModal {

if (self.state == kGameStatePlaying) {

[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];

[[CCDirector sharedDirector] pause];
}
}

- (void)adWhirlDidDismissFullScreenModal {

if (self.state == kGameStatePaused)
return;

else {
self.state = kGameStatePlaying;
[[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];
[[CCDirector sharedDirector] resume];

}
}

The first method is called when an ad is about to presented full-screen. Since we don’t want to mess up the player’s game, we pause the game here while the ad displays. Note we check here to see if the game is already paused before attempting to pause.

The second method is called when the user closes the ad, so it resumes the game if it is paused.

Next, let’s implement the methods to return the adWhirl application key and the view controller AdWhirl will present its ads in. Add the following methods next:

- (NSString *)adWhirlApplicationKey {
return @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
}

- (UIViewController *)viewControllerForPresentingModalView {
return viewController;
}

Replace the “xxx” in the adWhirlApplicationKey with the application key you got from AdWhirl (under “SDK Key”).

Next, implement the following methods to respond to receiving an ad and displaying it in the proper orientation:

-(void)adjustAdSize {
//1
[UIView beginAnimations:@"AdResize" context:nil];
[UIView setAnimationDuration:0.2];
//2
CGSize adSize = [adWhirlView actualAdSize];
//3
CGRect newFrame = adWhirlView.frame;
//4
newFrame.size.height = adSize.height;

//5
CGSize winSize = [CCDirector sharedDirector].winSize;
//6
newFrame.size.width = winSize.width;
//7
newFrame.origin.x = (self.adWhirlView.bounds.size.width - adSize.width)/2;

//8
newFrame.origin.y = (winSize.height - adSize.height);
//9
adWhirlView.frame = newFrame;
//10
[UIView commitAnimations];
}

- (void)adWhirlDidReceiveAd:(AdWhirlView *)adWhirlVieww {
//1
[adWhirlView rotateToOrientation:UIInterfaceOrientationLandscapeRight];
//2
[self adjustAdSize];

}

There’s a good amount of code here, so let’s explain it step by step, starting with the adjustAdSize method (which makes the ad appear on the bottom center of the screen):

Here we use the beginAnimations:context: to start animating the ad view. You call this on a UIView before changing one or more of its property values, such as its size, position, or opacity, to make those changes appear animated.

Get the actual size of the Ad and assign it in adSize.

Declare newFrame so we can assign a new size.

Set newFrame height equal to adSize height.

Declare winSize to hold window size parameters.

Set newFrame width to equal window width.

Position newFrame so that it is centered on the screen.

Position newFrame so that it appears on the bottom of the screen.

Set the adWhirlView’s frame to the new position we just calculated.

Calls the commitAnimations class method to end the animation block.

If you want your ad to appear in a different location, you can modify this code.

The adWhirlDidReceiveAd method works as follows:

Because of Space game in on landscape mode, we have to set the interface orientation to that. If your game in Portrait mode just comment the first line of code.

call adjustAdSize() method.

Just two methods left! Add the following 2 methods:

-(void)onEnter {
//1
viewController = [(AppDelegate *)[[UIApplication sharedApplication] delegate] viewController];
//2
self.adWhirlView = [AdWhirlView requestAdWhirlViewWithDelegate:self];
//3
self.adWhirlView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;

//4
[adWhirlView updateAdWhirlConfig];
//5
CGSize adSize = [adWhirlView actualAdSize];
//6
CGSize winSize = [CCDirector sharedDirector].winSize;
//7
self.adWhirlView.frame = CGRectMake((winSize.width/2)-(adSize.width/2),winSize.height-adSize.height,winSize.width,adSize.height);
//8
self.adWhirlView.clipsToBounds = YES;
//9
[viewController.view addSubview:adWhirlView];
//10
[viewController.view bringSubviewToFront:adWhirlView];
//11
[super onEnter];
}

-(void)onExit {
if (adWhirlView) {
[adWhirlView removeFromSuperview];
[adWhirlView replaceBannerViewWith:nil];
[adWhirlView ignoreNewAdRequests];
[adWhirlView setDelegate:nil];
self.adWhirlView = nil;
}
[super onExit];
}

According to Cocos2d CCNode class reference, onEnter is called when you first enter a scene (i.e. when the transition starts), and onExit is called when you exit a scene (i.e. when the transition ends).

In onEnter, the first thing we need to do is get the root view controller. There’s only one catch: the current cocos2d project templates do not assign the new root view controller to the UIWindow’s property, so normally it’s unavailable unless you expose it
in the AppDelegate class itself.

So go ahead and open AppDelegate.h and quickly declare a property for it:

@property (nonatomic, retain) RootViewController *viewController;

And switch to AppDelegate.m and synthesize this property:

@synthesize viewController;

Next, let’s return to onEnter and discuss it line by line:

Gets the view for the ad from AdWhirl and sets the layer as its delegate.

Sets the autosizing mask to center the ad.

Retrieves the configuration from adwhirl.com.

Gets the actual size of the Ad and assign it in adSize instance.

Declare winSize to hold window size parameters.

Sets the posion of AdWhirlView to the center bottom.

Makes sure any content is clipped to the ad view’s bounds.

Adds the ad view as a subview of the view controller.

Brings it to the front.

Calls onEnter from the superclass.

The onExit method just does cleanup – if an ad is visible, it removes it from the superview, makes it ignore any further ad requests, and sets the delegate to nil.

Compile and run, and you should see ads now in your game!





Where To Go From Here?

Here is an example
project with all of the code from the above tutorial.

Integrating Ads in your application not a bad idea and if you know how to market your app well, you will satisfied with the result. Here’s a screenshot for my AdMob account for 1 month for my first game Face
N’ Chase. Note this is only from AdMob – and more downloads equates to mo’ money!





Best of luck enabling AdWhirl in your Cocos2D game, and I hope you enjoyed this tutorial! If you have any questions or comments, please join the forum discussion below.



This is a blog post by iOS Tutorial Team member Ibrahim
Kteish, a student inspired by the iPhone with a passion for creating iOS software, and the cofounder of istockplus.com.

Category: iPhone

Tags: cocos2D, iPad, iPhone, sample
code, tutorial

I'd love to hear your thoughts!

26
Comments!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: