Integrating iAds into an iOS 4 iPhone App

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
An iOS 4 iPhone Graphics Drawing Tutorial using Quartz 2DAn Overview of iOS 4 iPhone Multitasking


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


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 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


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). Eying 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.

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 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 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.


Basic Rules for the Display of iAds

<google>IOSBOX</google> 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.

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.

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, Ctrl-click on the Frameworks entry in the Groups & Files panel and select the Add -> Existing Frameworks… menu option. In the resulting panel, scroll down to iAd.framework, select it and click on the Add button. The iAd.Framework will now appear in the frameworks list along with the other frameworks already included in the project.

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 compiler that within the view controller we will be implementing the delegate methods for the banner view protocol. Once the above changes have been made, save the file before proceeding.

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. Double click on the iAdAppViewController.xib file to launch Interface Builder and drag and drop a UITableView object into the View window as illustrated in the following figure:

An iOS 4 iPhone view with a table view


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 entry in the document window and dragging the resulting blue line to the table view in the View window. Release the line and select the tableView outlet from the resulting menu. With the user interface designed and the connection established, save the design file and exit from Interface Builder.

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):

#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.

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 it 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 available from the iAds inventory and that the application is behaving as intended.

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;
}

Save the file after implementing the methods and 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


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:

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 that you return YES if you wish to earn advertising revenue.

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:

- (void)bannerViewActionDidFinish:(ADBannerView *)banner
{
}

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
{
}


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
An iOS 4 iPhone Graphics Drawing Tutorial using Quartz 2DAn Overview of iOS 4 iPhone Multitasking