Integrating iAds into an iOS 4 iPhone App (Xcode 4)

Follow Techotopia on Twitter Bookmark and Share

From Techotopia

Jump to: navigation, search
PreviousTable of ContentsNext
Basic iPhone Animation using Core Animation (Xcode 4)An Overview of iOS 4 iPhone Multitasking (Xcode 4)


Purchase the fully updated iOS 7 edition of this book in eBook ($12.99) or Print ($32.99) format

iOS 7 App Development Essentails Print and eBook (ePub/PDF/Kindle) editions contain 89 chapters.

Buy eBook
Buy Print


In the first 11 months of business, Apple’s iTunes App Store reached 1 billion downloads. This actually turned out to be something of a slow start, and in the following year and a half the total number of downloads grew to 10 billion. Clearly this spectacular market growth would not have been possible without the availability of hundreds of thousands of high quality applications available to iPhone users in the App Store. Whilst some of these apps may have been developed by those with altruistic motives, it is most likely that the majority of the companies and individuals that invested the time and effort in creating apps did so in order to make money.

In terms of revenue generation options, the iTunes App Store eco-system provides a number of options. Perhaps the most obvious source of revenue for app developers involves charging the user an upfront fee for the application. Another option involves a concept referred to as “in-app purchase” whereby a user buys something from within the installed and running application. This typically takes the form of virtual goods (a packet of seeds in farming simulation or a faster car in a racing game) or premium content such as access to specific articles in a news application. Yet another option involves the inclusion of advertisements in the application. It is, of course, also common to generate revenue from a mixture of these three options. The subject of this chapter involves the use of advertising, specifically using Apple’s iAds system to incorporate adverts into an iOS 4 based iPhone application.

Contents




[edit] iOS iPhone Advertising Options

In the early days of the iOS application market, the dominant advertising network was provided by a company called AdMob. AdMob provided an SDK that enabled developers to incorporate AdMob sourced adverts into their iOS applications. In the early days AdMob came under some criticism for the quality of the ads that were served (which mostly took the form of ads for other iPhone applications). Eyeing AdMob’s dominance with envy and concern, both Apple and Google began negotiations to purchase the mobile advertising company. After lengthy discussions, very few details of which were ever made public, AdMob was acquired by Google. Having lost out on the AdMob acquisition, Apple quickly moved to purchase another mobile advertising network named Quattro Wireless. Part of the attraction of Quattro Wireless was the fact that the company handled mobile advertising for a number of major companies enabling Apple to target premium advertising with iAds. Apple eventually closed down the Quattro Wireless advertising network and used it as the basis for the iAds program which is now built into the iOS SDK ready for any developer to generate advertising revenue from premium quality adverts.

[edit] iAds Advertisement Formats

The iAds platform supports two sizes of banner ad and, with the introduction of the iOS 4.3 SDK, a full screen ad format called an interstitial.

The banner ads are intended to typically appear either at the top or bottom of the display and are provided in two formats so that ads may be displayed when the device is either in portrait or landscape orientation. iAds banner based advertising is incorporated into iOS iPhone applications through the ADBannerView class.

iAds interstitial adverts occupy the full device display and are primarily intended to be displayed when a user transitions from one screen to another within an application. Interstitial ads are incorporated into applications using the ADInterstitialView class.

[edit] Basic Rules for the Display of iAds

Apple provides the iAds framework as part of the iOS SDK and will serve ads to your application from an inventory of advertisers allowing you to keep 60% of the revenue.

Whilst implementation of iAds is relatively straightforward, there are some responsibilities that must be met by the application developer. In the first instance, the inclusion of an iAd advert on a particular screen of an iOS application does not guarantee that Apple will have an advert available to be displayed from the iAds network inventory. If no ad is available, the area of the screen occupied by the iAd object will remain blank. It is essential, therefore, that the application only displays an advert when the ad creative has been successfully downloaded onto the device.

As previously mentioned, iAd creative are available in formats suitable for display in both portrait and landscape orientations. If your application is capable of handling device rotation, it is important that the code supporting the display of iAds be able to switch the advert orientation to match that of the device.

Finally, once an ad appears in an application the user may choose to interact with it. This may, amongst other things, involve watching a movie clip, launching Safari to visit the advertiser’s web site or the display of an interactive view. It is entirely possible, therefore, that a user’s interaction with an iAds advert may result in your application being placed into the background or visually obscured for the duration of the interaction.

Given these requirements and possibilities it is important that the application code keep track of when an ad is displayed and the events that may unfold as a result of a user interacting with that ad. Fortunately this can easily be achieved by implementing a number of delegate methods defined in the ADBannerViewDelegate protocol as outlined later in this chapter.

[edit] Creating an Example iAds iPhone Application

In the remainder of this chapter we will work step by step through the creation of a simple iOS iPhone application that includes an iAd banner view advertisement. Begin this tutorial by launching Xcode and creating a new iOS iPhone application project named iAdApp using the View-based Application template.

The ultimate goal of this example is to create an application consisting of a table view and an iAd banner view. The banner will be configured to only appear when an ad is successfully downloaded from the iAds server and will change format to match the orientation of the device.

[edit] Adding the iAds Framework to the Xcode Project

Once the new project has been created, the first step is to make sure the iAds framework is included in the project. Failure to add this framework will result in compilation and linking errors when building the application.

To add the iAds framework, select the animate target located at the top of the project navigator panel. In the center pane, select the Build Phases tab and unfold the Link Binary With Libraries panel. Click on the ‘+’ button to display a list of existing frameworks, locate and select iAd.Framework and click the Add button. The iAd.Framework will now appear in the frameworks list along with the other frameworks already included in the project.

[edit] Configuring the View Controller

The next step is to declare an instance of the ADBannerView class and provide an outlet to the table view object that we will be placing in our user interface file in a later step. These steps are performed in the iAdAppViewController.h interface file. The necessary code is outlined below (note also the requirement to import the iAd/iAd.h header file):

#import <UIKit/UIKit.h>
#import <iAd/iAd.h>

@interface iAdAppViewController : UIViewController 
    <ADBannerViewDelegate>
{
        UITableView *tableView;
        ADBannerView *bannerView;
}
@property (nonatomic, retain) IBOutlet UITableView *tableView;
@end

In the above code we have also added a line that reads <ADBannerViewDelegate>. This indicates to the compiler that within the view controller we will be implementing the delegate methods for the banner view protocol.

[edit] Designing the User Interface

The next step is to design the user interface and connect the table view object to the tableView outlet declared in the view controller interface file above. Select the iAdAppViewController.xib file, display the Object library (View -> Utilities -> Object Library) and drag and drop a UITableView object into the View window as illustrated in the following figure:

Image:xcode_4_iad_example_table_view.jpg


Establish a connection between the table view object and the tableView outlet in the view controller by holding down the Ctrl key, clicking on the File’s Owner object and dragging the resulting blue line to the table view in the design panel. Release the line and select the tableView outlet from the resulting menu.

[edit] Creating the Banner Ad

For the purposes of this example we will create an instance of the ADBannerView in the viewDidLoad method of the view controller. Select the iAdAppViewController.m implementation file, remove the comment markers (/* and */) from around the viewDidLoad method and modify it as follows (note also the addition of the @synthesize directive for our tableView outlet and the code to release memory):

#import "iAdAppViewController.h"

@implementation iAdAppViewController
@synthesize tableView;
.
.
- (void)viewDidLoad {
    bannerView = [[ADBannerView alloc] 
          initWithFrame:CGRectZero];
    bannerView.requiredContentSizeIdentifiers = 
          [NSSet setWithObjects: 
          ADBannerContentSizeIdentifierPortrait,	
          ADBannerContentSizeIdentifierLandscape, nil];
    bannerView.delegate = self;
    [super viewDidLoad];
}
.
.
.
- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    bannerView = nil;
}
- (void)dealloc {
   [bannerView release];
   [super dealloc];
}

Within the body of the viewDidLoad method the code creates a new ADBannerView instance and assigns it to our bannerView variable. Next, the banner object is configured to download ad creative for both portrait and landscape orientations so that the ads can be switched instantly when the device is rotated. Finally, the view controller is declared as being the banner view’s delegate. The remaining methods ensure that we release any memory allocated to the bannerView object when the application exits.

[edit] Displaying the Ad

If we were to compile and run our application now, no ad would be visible because we have not, as yet, taken any steps to display it. As previously mentioned, an ad should not be displayed to the user until creative has been successfully downloaded from the iAds server. On successful download of an ad, the bannerViewDidLoadAd method is called. By implementing this delegate method in our view controller, therefore, we can make sure the ad is displayed only when an ad is ready. Within the iAdAppViewController.m file, implement this method as follows:

- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
   tableView.tableHeaderView = bannerView;
}

All that this method needs to do is assign the bannerView ad object as the header of our tableView component in the user interface.

Build and run the application in the iOS Simulator to verify that the code works:


An iOS 4 iPhone app running with an iAds banner diaplayed in portrait


In the event that the ad does not appear, open the Console window application (located in the Applications/Utilities folder of your Mac OS X system) and check for error messages. The most likely error is that an ad was not available from the iAds inventory and that the application is behaving as intended.

[edit] Changing Ad Format during Device Rotation

So far we have not written any code to allow our application display to rotate and to change the ad format between portrait and landscape. An ideal location to implement this behavior is within the shouldAutorotateToInterfaceOrientation method of the view controller. Once again, remove the comment markers (/* */) from around the template method in iAdAppViewController.m before modifying the code as follows:

- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
  if (UIInterfaceOrientationIsLandscape(interfaceOrientation))
         bannerView.currentContentSizeIdentifier =
         ADBannerContentSizeIdentifierLandscape;
  else
         bannerView.currentContentSizeIdentifier =
         ADBannerContentSizeIdentifierPortrait;
  return YES;
}

After implementing the methods build and run the application once again in the iOS Simulator. Once the app has loaded and an ad banner has appeared, rotate the device using the Hardware -> Rotate Left menu option. On switching to landscape, the ad should change dynamically to landscape format as illustrated in the following figure:


An iOS 4 iPhone app running with an iAds banner diaplayed in landscape


[edit] Implementing the Delegate Methods

In order to implement the ADBannerViewDelegate protocol there are a few more methods that should be implemented within the view controller. What these methods actually do will depend on the requirements of the application and in some cases it may not even be necessary for these methods to do anything. We have already implemented one of these methods (the bannerViewDidLoadAd method). The other methods are as follows:

[edit] bannerViewActionShouldBegin

This method is triggered when the user touches the iAds banner in your application. If the willLeave argument passed through to the method is YES then your application will be placed into the background while the user is taken elsewhere to interact with or view the ad. If the argument is NO then the ad will be superimposed over your running application in which case the code in this method may optionally suspend the screen output until the user returns.

- (BOOL)bannerViewActionShouldBegin:
(ADBannerView *)banner 
willLeaveApplication:(BOOL)willLeave
{
    return YES;
}

If the ad places the application into the background, the application will be resumed automatically once the action is completed. To prevent the ad from performing the action, return NO from this method, though it is strongly recommended by Apple that you return YES if you wish to earn advertising revenue.

[edit] bannerViewActionDidFinish

This method is called when the ad view removes the ad content currently obscuring the application interface. If the application was paused during the ad view session this method can be used to resume activity:

</pre> - (void)bannerViewActionDidFinish:(ADBannerView *)banner { } </pre>

[edit] bannerView:didFailToReceiveAdWithError

This method is triggered when an advertisement could not be loaded from the iAds system (perhaps due to a network connectivity issue). If you have already taken steps to only display an ad when it has successfully loaded it is not typically necessary to implement the code for this method.

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
}


Purchase the fully updated iOS 7 edition of this book in eBook ($12.99) or Print ($32.99) format

iOS 7 App Development Essentails Print and eBook (ePub/PDF/Kindle) editions contain 89 chapters.

Buy eBook
Buy Print



PreviousTable of ContentsNext
Basic iPhone Animation using Core Animation (Xcode 4)An Overview of iOS 4 iPhone Multitasking (Xcode 4)
Views
Personal tools

Find us on Facebook