Reputation: 2649
I'm currently working on a Spritekit project.
I have 3 scenes: MainMenu, Game, Gameover
I would like to have the iAd show only when the user is on the Game scene and the Gameover scene.
This is my current code for iAd in my ViewController.m:
- (void) viewWillLayoutSubviews
{
// For iAds
_bannerView = [[ADBannerView alloc] initWithAdType:ADAdTypeBanner];
_bannerView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
_bannerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
_bannerView.delegate = self;
_bannerView.hidden = YES;
[self.view addSubview:_bannerView];
}
#pragma mark - iAds delegate methods
- (void)bannerViewDidLoadAd:(ADBannerView *)banner {
// Occurs when an ad loads successfully
_bannerView.hidden = NO;
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error {
// Occurs when an ad fails to load
_bannerView.hidden = YES;
}
- (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave {
// Occurs when the user taps on ad and opens it
return YES;
}
- (void)bannerViewActionDidFinish:(ADBannerView *)banner {
// Occurs when the ad finishes full screen
}
The problem is, since the MainMenu scene is the first scene to display, the banner shows there upon successfully loading an ad. How do I make it only appear when the user is on the Game scene and the Gameover scene?
Upvotes: 2
Views: 435
Reputation: 4046
The best approach here is to use NSNotificationCenter:
Register notification in your - (void) viewWillLayoutSubviews
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"hideAd" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:@"showAd" object:nil];
And handle the Notification here
- (void)handleNotification:(NSNotification *)notification
{
if ([notification.name isEqualToString:@"hideAd"])
{
// hide your banner;
}else if ([notification.name isEqualToString:@"showAd"])
{
// show your banner
}
}
And in your scense
[[NSNotificationCenter defaultCenter] postNotificationName:@"showAd" object:nil]; //Sends message to viewcontroller to show ad.
[[NSNotificationCenter defaultCenter] postNotificationName:@"hideAd" object:nil]; //Sends message to viewcontroller to hide ad.
Thanks and best of luck.
Upvotes: 5