There are a couple of tricks to implementing iAd in iPhone applications that are not 100% spelled out in the documentation provided by Apple. If you do not implement right your app will crash on phones running older versions of iOS such as iOS4.1 and iOS3.
For your .h file:
#import <UIKit/UIKit.h>;
#import <iAd/iAd.h>;
@interface iAdViewController : UIViewController <ADBannerViewDelegate> {
ADBannerView *adView;
BOOL bannerIsVisible;
}
@property (nonatomic,assign) BOOL bannerIsVisible;
@end
In the .m file you need the following:
- (void) viewWillAppear:(BOOL)animated {
// check if iAd is available
Class classAdBannerView = NSClassFromString(@"ADBannerView");
if (classAdBannerView) {
// create iAd
ADBannerView *bannerView = [[classAdBannerView alloc] initWithFrame:CGRectZero];
if (&ADBannerContentSizeIdentifierPortrait != nil) {
// NEWER
DLog(@"NEWER");
bannerView.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifierPortrait];
bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
} else {
// OLDER
DLog(@"OLDER");
bannerView.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifier320x50];
bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;
}
bannerView.delegate=self;
self.adView = bannerView;
[self.view addSubview:adView];
self.bannerIsVisible=NO;
[bannerView release];
}
[super viewWillAppear: animated];
}
I am creating the bannerView programatically in order to have the app also work on pre iOS 4.1 devices. The check for ADBannerContentSizeIdentifierPortrait is to see if the user is using iOS 4.1 or newer iOS. In iOS 4.1 the identifiers were based on size – but in newer iOS the iPad got iAds and the size no longer made sense – thus the landscape/portrait designations.
Finally – if your app supports multiple interface orientations – you need to let the banner know that the device rotated so it can show the right size ad.
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
if (&ADBannerContentSizeIdentifierPortrait != nil) {
// NEWER
DLog(@"NEWER");
if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation))
adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierLandscape;
else
adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
} else {
// OLDER
DLog(@"OLDER");
if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation))
adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier480x32;
else
adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;
}
}