2012年1月10日

【iPhone】AdMobの広告を表示する(2)

こんばんわ。今日も仕事してませんでした。

SDKの導入とframeworkの追加は終了したと思いますので、
朝の続きを解説していきます。


AppDelegate.h

#import <UIKit/UIKit.h>
#import "GADBannerView.h"

@class WebViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    UIWindow *window;
    UINavigationController *navController;
    WebViewController *webViewController;
    // Declare one as an instance variable
    GADBannerView *bannerView_;
}

@property (nonatomic, retain) UIWindow *window;

@property (nonatomic, retain) UINavigationController *navController;

@property (nonatomic, retain) WebViewController *webViewController;

@end

そして、

AppDelegate.m

の書き出し部分
#import "AppDelegate.h"
#import "WebViewController.h"

#define MY_BANNER_UNIT_ID @"xxxxxxxxxxxx";

@implementation AppDelegate

@synthesize window = _window;

@synthesize navController = _navController;

@synthesize webViewController = _webViewController;

さらに、下記のように、メソッド内に記述していきます。
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    /**********************************************************
     * set admob
     **********************************************************/
    bannerView_ = [[GADBannerView alloc]
                   initWithFrame:CGRectMake(0.0,
                                            self.window.frame.size.height -
                                            GAD_SIZE_320x50.height,
                                            GAD_SIZE_320x50.width,
                                            GAD_SIZE_320x50.height)];
    
    // Specify the ad's "unit identifier." This is your AdMob Publisher ID.
    bannerView_.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.
    bannerView_.rootViewController = self.navController;
    [self.window addSubview:bannerView_];
    
    // Initiate a generic request to load it with an ad.
    GADRequest *request = [[GADRequest alloc] init];
    request.testDevices = [NSArray arrayWithObjects:
                           GAD_SIMULATOR_ID,
                           nil];
    [bannerView_ loadRequest:request];
    // Do any additional setup after loading the view from its nib.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
    bannerView_ = nil;
}

変数名等はあわせて変えてください。

AppDelegateで設定しておくと、アプリ中は常に表示するようになるので、
いろいろな場所に書かなくて済み楽ですね。

では次回もよろしくお願いします。