简体   繁体   中英

Hide Admob banner in iOS with SpriteKit

I'm using a 2d game engine called Sprite kit within Xcode and i want to hide my ad banner in specific areas such as the game scene and then show it once it's game over for the player. But i'm having trouble trying to access the hidden property of the banner within other scenes/classes.

GameViewController.h

#import <UIKit/UIKit.h>

#import <SpriteKit/SpriteKit.h>

#import <GoogleMobileAds/GoogleMobileAds.h>

#import <AVFoundation/AVFoundation.h>

@interface GameViewController : UIViewController

-(void) hideBanner;

@end

GameViewController.m

@implementation GameViewController

-(void) hideBanner {
    self.bannerView.hidden = YES;   
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Create a banner ad and add it to the view hierarchy.

    self.bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait];

    //TEST UNIT ID

    self.bannerView.adUnitID = @"ca-app-pub-3940256099942544/2934735716";
    self.bannerView.rootViewController = self;

    [self.view addSubview:self.bannerView];

    GADRequest *request = [GADRequest request];

    request.testDevices = @[ @"*log id*" ];

    [self.bannerView loadRequest:request];
}

GameScene.h

@class GameViewController;

@interface GameScene : SKScene <SKPhysicsContactDelegate>

@property (strong, nonatomic) GameViewController *gameViewController;

@end

GameScene.m

//This line of code will be executed in the "performGameOver" method but it does not work and the banner is still shown? 
    [self.gameViewController hideBanner];

You should use NSNotification

In viewController.m

 - (void)handleNotification:(NSNotification *)notification { 
if ([notification.name isEqualToString:@"hideAd"]) {
    [self hidesBanner];
}else if ([notification.name isEqualToString:@"showAd"]) {
    [self showBanner];
}}

-(void)hidesBanner {

    NSLog(@"HIDING BANNER");
    [adView setAlpha:0];
    self.bannerIsVisible = NO;
}

-(void)showsBanner {

    NSLog(@"SHOWING BANNER");
    [adView setAlpha:1];
    self.bannerIsVisible = YES;
}

In your scene:

Sends message to viewcontroller to show ad.

[[NSNotificationCenter defaultCenter] postNotificationName:@"showAd" object:nil]; 

Sends message to viewcontroller to hide ad.

[[NSNotificationCenter defaultCenter] postNotificationName:@"hideAd" object:nil]; 

More info:

https://stackoverflow.com/a/21967530/4078517

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM