本当は毎回ViewControllerにAdMobを表示させるコードを書くのが面倒で、AppDelegateでどうにか楽にできないかなーと調べていたら、自分が思っていた以上に素敵なやり方がありました。
毎回コードを書く必要がなく、かつUITabBarでタブを使っている場合タブ切り替えの際に毎回AdMobをロードされていたのですが、これもやらなくてすむ方法。
AppDelegate.m に以下を追記
// *UITabBarControllerを取得する
UITabBarController *tabBarController = (UITabBarController*)self.window.rootViewController;
GADBannerView *_gadBannerView;
_gadBannerView = [[GADBannerView alloc]
initWithFrame:CGRectMake(0.0,
20,
GAD_SIZE_320x50.width,
GAD_SIZE_320x50.height)];
// Specify the ad's "unit identifier." This is your AdMob Publisher ID.
_gadBannerView.adUnitID = @"MY_BANNER_UNIT_ID";
// Let the runtime know which UIViewController to restore after taking
// the user wherever the ad goes and add it to the view hierarchy.
_gadBannerView.rootViewController = tabBarController;
[tabBarController.view addSubview:_gadBannerView];
// Initiate a generic request to load it with an ad.
[_gadBannerView loadRequest:[GADRequest request]];
ちなみに GADBannerView.h は以前書いた「iOSアプリにAdMobとGoogleAnalyticsを導入するカンタンな方法」の通り、(アプリ名)-Prefix.pch でincludeしています。
これで毎回ソースを書かなくても、すべてのViewでAdMobが表示される、はず。
さらには、「iOSアプリにAdMobとGoogleAnalyticsを導入するカンタンな方法」で書いた時とくらべて、AdMobとGoogleAnalyticsを表示させる時、ViewController.m に追加しないといけないのは以下だけになりました。
#import "AppDelegate.h"
//GoogleAnalyticsのページ名
self.trackedViewName = @"TOPページ";
どっかのタイミングで、GoogleAnalyticsのページ名を追記するのも動的化したいなあ。
こちらを参考にさせて頂きました。
アプリ開発:UITabBarControllerへの効果的な広告の貼り方 | JOHN DOE
プログラマメモ2: UITabBarControllerなアプリの場合の広告(admob)の置き方


コメント