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

From Techotopia
Revision as of 20:01, 27 October 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0">" to "<table border="0" cellspacing="0" width="100%">")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
PreviousTable of ContentsNext
An iOS 4 iPad Core Animation Tutorial (Xcode 4)An Overview of iOS 4 iPad Multitasking (Xcode 4)


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 introduction to this book we spent some time talking about the fact that the iPad is more than just a device and that it is, in fact, just the most tangible part of vast ecosystem. A key component of that ecosystem is the iAds platform and no book on the subject of iPad app development would be complete without at least one chapter dedicated to it.

The subject of this chapter involves the use of advertising, specifically using Apple’s iAds system, to incorporate adverts into an iOS 4 based iPad application.


Contents


Making Money from an iPad Application

The design, development and testing of an iPad application is a significant undertaking involving a considerable amount of time and effort. The developer of an iPad app typically has to make a choice regarding the methods that will be used to both recoup those development costs and, presumably, generate both an ongoing revenue stream and profit.

In terms of revenue generation options, Apple’s iPad and iPhone ecosystem 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 selection of revenue generating options is something of a delicate balancing act. If the main goal is to generate advertising revenue then charging a high purchase price may reduce the number of users that download the app, thereby limiting advertising revenue opportunities. Making the app free, on the other hand, and relying solely on advertising revenue may not generate sufficient income to justify the upfront development costs of the application. The correct model will depend to a large extent on the type of application and the target market.

The complexities of choosing the right balance of revenue streams aside the implementation of iAds advertising in an iPad application is actually a very straightforward process.

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


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 iPad applications through the ADBannerView class.

The iAds interstitial format advertisements 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.

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

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

Creating an Example iAds iPad Application

In the remainder of this chapter we will work step by step through the creation of a simple iOS iPad application that includes an iAd banner view advertisement capable of displaying in both portrait and landscape orientation.

Begin this tutorial by launching Xcode and creating a new iOS iPad 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, select the iAdApp 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.

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.

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:


The user interface for an example iAds iPad app


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.

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.

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 iPad Simulator to verify that the code works:

An Example iPad App showing a portrait iAds advert


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.

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. By default Xcode should have configured this method to return YES to indicate all orientations are supported by the application. Select the iAdAppViewController.m file and modify this method so that it reads 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 iPad Simulator. Once the app has loaded and a banner advertisement 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 Example iPad App showing a lanscape iAds advert


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 by Apple 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 iPad Core Animation Tutorial (Xcode 4)An Overview of iOS 4 iPad Multitasking (Xcode 4)