AdMob in all my view controllers?

回眸只為那壹抹淺笑 提交于 2019-12-05 10:23:56

What you want here is a GADBannerView singleton of sorts. You can probably create a wrapping class to act as a singleton for your adView, so something like:

@interface GADMasterViewController : UIViewController {
  GADBannerView *adBanner_;
  BOOL didCloseWebsiteView_;
  BOOL isLoaded_;
  id currentDelegate_;
}

And just make sure that GADMasterViewController always returns a singleton:

+(GADMasterViewController *)singleton {
  static dispatch_once_t pred;
  static GADMasterViewController *shared;
  // Will only be run once, the first time this is called
  dispatch_once(&pred, ^{
    shared = [[GADMasterViewController alloc] init];
  });
  return shared;
}

Have a method which resets the current view controller that's holding on to the adView:

-(void)resetAdView:(UIViewController *)rootViewController {
  // Always keep track of currentDelegate for notification forwarding
  currentDelegate_ = rootViewController;

  // Ad already requested, simply add it into the view
  if (isLoaded_) {
    [rootViewController.view addSubview:adBanner_];
  } else {

    adBanner_.delegate = self;
    adBanner_.rootViewController = rootViewController;
    adBanner_.adUnitID = kSampleAdUnitID;

    GADRequest *request = [GADRequest request];
    [adBanner_ loadRequest:request];
    [rootViewController.view addSubview:adBanner_];
    isLoaded_ = YES;
  }
}

Then displaying your ad is just a matter of:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    shared = [GADMasterViewController singleton];
    [shared resetAdView:self];
}

You probably need to set up a delegate to forward notifications as well since the AdMob SDK doesn't act well to delegates changing on it in the middle of a request.

You can find a blog post about this here.

I don't know how adMob works but like everything else you can create a BaseViewController in which you can add your adMob(in the viewDidLoad method) and then all the other viewControllers can subClass this BaseViewController. just call [super viewDidLoad]; in the viewDidLoad methods of your viewControllers and you will have it...

hoping this sorts your problem... :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!