I want to use AdMob in my app and I have 4 viewControllers (in 4 tab items) where I want to make it visible. The way the sample shows, every ViewController needs to make ins
The AppDelegate aproach is a nice approach but you should not retain the instance of the admob in every viewcontroller and release the same in the viewDidUnload
method. Instead of doing this just add the admob's view in every viewcontroller's viewDidLoad
method as a subview. In this manner there will be only one instance of the Admob's view in the AppDelegate.
Hope this helps you.
You can declare your admob view in appDelegate and add it as subview to window. Refer to admob view from VC through appDelegate
Sure, that would work but the only problem is that when you update the delegate for the ad, it will not actually pick up the new delegate for the ad unless you explicitly make a new ad request, so your old views will be receiving any notifications from the ad. I'd recommend the approach of making an adMob singleton that then forwards any delegate notifications to the right view.
So creating a class called GADMasterViewController
(make sure it follows the GADBannerViewDelegate
protocol too) or something which has a static initializer as so:
+(GADMasterViewController *)singleton {
static dispatch_once_t pred;
static GADMasterViewController *shared = nil;
dispatch_once(&pred, ^{
shared = [[GADMasterViewController alloc] init];
});
return shared;
}
Then in the initializer you can initialize a single GADBannerView as a property of this singleton:
-(id)init
{
if (self = [super init])
{
self.adBanner = [[GADBannerView alloc]
initWithFrame:CGRectMake(0.0,
0.0,
GAD_SIZE_320x50.width,
GAD_SIZE_320x50.height)];
// Has an ad request already been made
self.isLoaded = NO;
}
return self;
}
Then you can have a method which sets your new adView as the currentDelegate as such:
-(void)resetAdView:(UIViewController<GADBannerViewDelegate> *)rootViewController {
if (self.isLoaded) {
currentDelegate_ = rootViewController;
[rootViewController.view addSubview:self.adBanner];
}
else {
// The delegate to forward any notifications too
currentDelegate_ = rootViewController;
self.adBanner.delegate = self;
self.adBanner.rootViewController = rootViewController;
self.adBanner.adUnitID = kSampleAdUnitID;
GADRequest *request = [GADRequest request];
[self.adBanner loadRequest:request];
[rootViewController.view addSubview:self.adBanner];
self.isLoaded = YES;
}
}
At this point, you just want to forward any notifications which you get to the right viewController, so one example would be:
- (void)adViewDidReceiveAd:(GADBannerView *)view {
if ([currentDelegate_ respondsToSelector:@selector(adViewDidReceiveAd:)]) {
[currentDelegate_ adViewDidReceiveAd:view];
}
}
In ViewControllerX
(one of your 4 ViewControllers), you could just add it to your view hierarchy using:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
shared = [GADMasterViewController singleton];
[shared resetAdView:self];
}