How to create a global reference for iAd and implement in multiple Viewcontrollers

前端 未结 3 576
花落未央
花落未央 2021-01-12 19:23

I\'m having 5 ViewControllers in each of that i have to display iAd,so that i have to implement iAd code in each ViewControllers. Instead of that if i create

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 20:12

    In the AppDelegate.h:

    #import 
    
    @interface AppDelegate : UIResponder 
    {
        ADBannerView *_bannerView;
    ...
    ...
    }
    
    @property (nonatomic, retain) ADBannerView *_bannerView;
    

    In the AppDelegate.m:

    @synthesize _bannerView;
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    ...
        if ([ADBannerView instancesRespondToSelector:@selector(initWithAdType:)]) {
            self._bannerView = [[ADBannerView alloc] initWithAdType:ADAdTypeBanner];
        } else {
            self._bannerView = [[ADBannerView alloc] init];
        }
    ...
    }
    

    In the view controllers that you need to add iAd, create a container UIView with name 'vwAd' and make the connection in xib file where you want to display iAds.

    @interface ViewController : UIViewController
    {
        IBOutlet UIView *vwAd;
    ...
    ...
    }
    
    - (void)layoutAnimated:(BOOL)animated
    {
        CGRect contentFrame = self.view.bounds;
        if (contentFrame.size.width < contentFrame.size.height) {
            self.appDelegate._bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
        } else {
            self.appDelegate._bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierLandscape;
        }
    
        CGRect bannerFrame = self.appDelegate._bannerView.frame;
        if (self.appDelegate._bannerView.bannerLoaded) {
            bannerFrame.origin.y = 0;
        } else {
            bannerFrame.origin.y = vwAd.frame.size.height;
        }
    
        [UIView animateWithDuration:animated ? 0.25 : 0.0 animations:^{
            self.appDelegate._bannerView.frame = bannerFrame;
        }];
    }
    
    
    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        ...
    
        [self.appDelegate._bannerView removeFromSuperview];
        self.appDelegate._bannerView.delegate = nil;
        self.appDelegate._bannerView.delegate = self;
        [vwAd addSubview:self.appDelegate._bannerView];
        [self layoutAnimated:NO];
    }
    

    Please also review iAdSuite examples from Apple. Original layoutAnimated function can be found in iAdSuite examples. Do not forget to add the delegate functions from iAdSuite example into your view controller.

提交回复
热议问题