Cocos2d-xにAdMob (インタースティシャル) を導入する方法 - iOS編
前回のバナー導入に引き続き今度はインタースティシャル編。AdMobバナーが表示出来ていれば、コードを追記していくだけで対応できる。
まずは検証として、起動したらインタースティシャル広告がでるようにしてみるコードはこちら。(バナー関連のコードは削除してインタースティシャルで必要となるコードのみ記載)
extern "C"{ #import <GoogleMobileAds/GADInterstitial.h> }; @interface AppController() @property(nonatomic, strong) GADInterstitial *interstitial; @end @implementation AppController ... - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... self.interstitial = [[GADInterstitial alloc] initWithAdUnitID:@"ca-app-pub-xxxxx/xxxxx"]; GADRequest *request = [GADRequest request]; request.testDevices = @[ kGADSimulatorID ]; [self.interstitial loadRequest:request]; // 2秒後に広告表示 for test [NSTimer scheduledTimerWithTimeInterval:(2.0) target:self selector:@selector(showAd) userInfo:nil repeats:NO]; app->run(); return YES; } - (void)showAd{ if([self.interstitial isReady]){ [self.interstitial presentFromRootViewController:_viewController]; } }
任意のタイミングで広告表示
cocos2d-x側 (C++) からObjective-Cのコードを呼び出すと、任意のタイミングでインタースティシャルを表示することができる。まずは下記の2ファイルを追加。
AdMobHelper.h
#ifndef __ADMOBHELPER_H__ #define __ADMOBHELPER_H__ class AdMobHelper { public: static void launchInterstitial(); }; #endif
AdMobHelper.mm
#include "AdMobHelper.h" #include "AppController.h" void AdMobHelper::launchInterstitial(){ AppController *appController = (AppController *)[UIApplication sharedApplication].delegate; [appController launchInterstitial]; }
AppControllerを修正
複数回表示できるよう、呼び出されるメソッド内部で広告のロードを行う。
extern "C"{ #import <GoogleMobileAds/GADInterstitial.h> }; @interface AppController() <GADInterstitialDelegate> @property(nonatomic, strong) GADInterstitial *interstitial; @end @implementation AppController ... - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ... [self loadInterstitial]; app->run(); return YES; } - (void)loadInterstitial{ self.interstitial = [[GADInterstitial alloc] initWithAdUnitID:@"ca-app-pub-xxxxx/xxxxx"]; self.interstitial.delegate = self; GADRequest *request = [GADRequest request]; request.testDevices = @[ kGADSimulatorID ]; [self.interstitial loadRequest:request]; } - (void)launchInterstitial{ if([self.interstitial isReady]){ [self.interstitial presentFromRootViewController:_viewController]; } } - (void)interstitialDidDismissScreen:(GADInterstitial *)ad{ [self loadInterstitial]; } - (void)interstitial:(GADInterstitial *)ad didFailToReceiveAdWithError:(GADRequestError *)error{ NSLog(@"%@", error); }
最後に、サンプルにあるHelloWorldSceneのクローズボタンを押したタイミングでこのメソッドを実行するようにする。
void HelloWorld::menuCloseCallback(Ref* pSender){
AdMobHelper::launchInterstitial();
}