如何在Cocos-SpriteBuilder中添加iAd

时间:2014-02-14 04:53:39

标签: ios cocos2d-iphone iad spritebuilder

我正在使用SpriteBuilder(它与Cocos2d v3.0集成)。我构建了一个应用程序,现在我想在我调用它时弹出最顶部的iAd,并在我告诉它时隐藏它。最简单的方法是什么?

请记住我正在使用SpriteBuilder和Cocos2d。仅仅因为我使用SpriteBuilder并不意味着我也没有使用Xcode 5。我也完全参与了Xcode。 SpriteBuilder没有为我编写代码,我这样做。

1 个答案:

答案 0 :(得分:8)

将iAd框架添加到您的依赖项中。

在游戏场景的头文件中,添加ADBannerViewDelegate,例如:

@interface MainScene : CCNode <CCPhysicsCollisionDelegate, ADBannerViewDelegate>

在您的实现文件中,添加实例变量_bannerView:

@implementation MainScene {
    ADBannerView *_bannerView;
}    

最后,插入iAD代码(带有一些cocos2d调整)。这是我在纵向模式下使用顶部横幅进行游戏的实现。没有隐藏方法,但它很容易实现。

# pragma mark - iAd code

-(id)init
{
    if( (self= [super init]) )
    {
        // On iOS 6 ADBannerView introduces a new initializer, use it when available.
        if ([ADBannerView instancesRespondToSelector:@selector(initWithAdType:)]) {
            _adView = [[ADBannerView alloc] initWithAdType:ADAdTypeBanner];

        } else {
            _adView = [[ADBannerView alloc] init];
        }
        _adView.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifierPortrait];
        _adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
        [[[CCDirector sharedDirector]view]addSubview:_adView];
        [_adView setBackgroundColor:[UIColor clearColor]];
        [[[CCDirector sharedDirector]view]addSubview:_adView];
        _adView.delegate = self;
    }
    [self layoutAnimated:YES];
    return self;
}


- (void)layoutAnimated:(BOOL)animated
{
    // As of iOS 6.0, the banner will automatically resize itself based on its width.
    // To support iOS 5.0 however, we continue to set the currentContentSizeIdentifier appropriately.
    CGRect contentFrame = [CCDirector sharedDirector].view.bounds;
    if (contentFrame.size.width < contentFrame.size.height) {
        _bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
    } else {
        _bannerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierLandscape;
    }

    CGRect bannerFrame = _bannerView.frame;
    if (_bannerView.bannerLoaded) {
        contentFrame.size.height -= _bannerView.frame.size.height;
        bannerFrame.origin.y = contentFrame.size.height;
    } else {
        bannerFrame.origin.y = contentFrame.size.height;
    }

    [UIView animateWithDuration:animated ? 0.25 : 0.0 animations:^{
        _bannerView.frame = bannerFrame;
    }];
}

- (void)bannerViewDidLoadAd:(ADBannerView *)banner {
    [self layoutAnimated:YES];
}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error {
    [self layoutAnimated:YES];
}