Sunday, October 10, 2010

How to add iAds to your iOS app

If you've tried to add an iAd to your iPhone / iPod Touch / iPad and been rejected because the app didn't automatically hide when no advertisements were available, here are the instructions how to make that happen.

Note, if you chose to make your iAd appear programmatically, then Apple will have already sent you some basic hints about how to do this.  But if you used Interface Builder to place / orient your iAd widget like I did, the task is much simpler, as explained in the post by That Don Guy linked to above and the advice from Apple will only serve to confuse (though is good to know for an advanced developer).

But let's say you want to expand a widget (of UIView type) over the space where the iAd would normally be when no iAd is available?  The easiest way I've found to do this is to use Interface Builder to lay out the UIView as if the iAd was there, but make sure the iAd starts hidden by checking the box in the Attributes properties for it.

Then, in your module header file for the parent UIViewController containing these widgets, add a variable to hold the default size of the UIView as designed in Interface Builder:
CGFloat default_view_height;

Once the header file is modified, it's time to update the module.  First, we need to calculate the default_view_height when the view first displays. We can do this in our - (void)viewDidLoad handler:
// Store the UIView height to restore it if the iAd disappears
default_view_height = my_view.frame.size.height;
where my_view is the outlet for the UIView you wish to expand.

Now, we need to expand the UIView into the iAd space by default since the iAd starts hidden; again we do this in the - (void)viewDidLoad slot:
// Since the iAd starts hidden, make the UIView full-sized
my_view.frame = CGRectMake(my_view.frame.origin.x,
my_view.frame.origin.y,
my_view.frame.size.width,
iad_view.frame.origin.y +
iad_view.frame.size.height -
my_view.frame.origin.y);
where iad_view is the outlet for your iAd.

Now you need to implement the 2 ADBannerViewDelegate handlers for when an iAd becomes available and when none are any more.  You should already have these handlers from That Don Guy's instructions; we're just going to add some code to take care of the expansion:
- (void) bannerViewDidLoadAd:(ADBannerView *) banner {
// Shrink web view to allow iAd space
my_view.frame = CGRectMake(my_view.frame.origin.x,
my_view.frame.origin.y,
my_view.frame.size.width,
default_view_height);

iad_view.hidden = NO;
}

- (void) bannerView:(ADBannerView *) banner didFailToReceiveAdWithError:(NSError *) error {
iad_view.hidden = YES;

// Expand web view to fill space
my_view.frame = CGRectMake(my_view.frame.origin.x,
my_view.frame.origin.y,
my_view.frame.size.width,
iad_view.frame.origin.y +
iad_view.frame.size.height -
my_view.frame.origin.y);
}

Compile your iApp and Bob's your uncle!

No comments:

Post a Comment