2015-01-14 4 views
1

Я реализовал код iAd suite и получил все, что работает. Однако, когда объявление загружено неправильно, просмотр содержимого не изменяется (поскольку пространство просмотра баннера больше не требуется). Кроме того, я хочу это также, когда пользователь покупает версию «без рекламы» моего приложения. Затем баннер должен быть удален во время выполнения. Как я могу это сделать? Вот мой код (большая часть части из ОВР люкс 1: 1 скопированной):iAd suite: Как скрыть основной баннер?

//

#import "IAdViewController.h" 

@interface IAdViewController() 

@property (nonatomic, strong) IBOutlet UIView *contentView; 
// contentView's vertical bottom constraint, used to alter the contentView's vertical size when ads arrive 
@property (nonatomic, strong) IBOutlet NSLayoutConstraint *bottomConstraint; 

@end 

@implementation IAdViewController 

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    if(![[[NSUserDefaults standardUserDefaults] objectForKey:kInAppPurchaseNoAds] boolValue]){ 

     _bannerView = [[Singletons sharedInstance] bannerView]; 
     _bannerView.delegate = self; 
     [self.view addSubview:_bannerView]; 
    } 
} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 
    [self layoutAnimated:NO]; 
} 

- (void)viewDidDisappear:(BOOL)animated 
{ 
    [super viewDidDisappear:animated]; 
} 

//Handle the in app purchases 
- (void)viewWillAppear:(BOOL)animated { 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(productPurchased:) name:IAPHelperProductPurchasedNotification object:nil]; 
} 

- (void)viewWillDisappear:(BOOL)animated { 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

- (void)layoutAnimated:(BOOL)animated 
{ 
    CGRect contentFrame = self.view.bounds; 

    // all we need to do is ask the banner for a size that fits into the layout area we are using 
    CGSize sizeForBanner = [_bannerView sizeThatFits:contentFrame.size]; 

    // compute the ad banner frame 
    CGRect bannerFrame = _bannerView.frame; 
    if (_bannerView.bannerLoaded) { 

     // bring the ad into view 
     contentFrame.size.height -= sizeForBanner.height; // shrink down content frame to fit the banner below it 
     bannerFrame.origin.y = contentFrame.size.height; 
     bannerFrame.size.height = sizeForBanner.height; 
     bannerFrame.size.width = sizeForBanner.width; 

     // if the ad is available and loaded, shrink down the content frame to fit the banner below it, 
     // we do this by modifying the vertical bottom constraint constant to equal the banner's height 
     // 
     NSLayoutConstraint *verticalBottomConstraint = self.bottomConstraint; 
     verticalBottomConstraint.constant = sizeForBanner.height; 
     [self.view layoutSubviews]; 

    } else { 
     // hide the banner off screen further off the bottom 
     bannerFrame.origin.y = contentFrame.size.height; 
    } 

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

- (void)productPurchased:(NSNotification *)notification { 
    if([[[NSUserDefaults standardUserDefaults] objectForKey:kInAppPurchaseNoAds] boolValue]){ 
     [_bannerView removeFromSuperview]; 
     _bannerView.delegate = nil; 
     _bannerView = nil; 
     [self layoutAnimated:YES]; 
    } 
} 

- (void)viewDidLayoutSubviews 
{ 
    [self layoutAnimated:[UIView areAnimationsEnabled]]; 
} 

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

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

ответ

1

Я думаю подмигнули в руководствах по проектированию, которые вы должны анимировать знамя, чтобы двигаться и вне. Кроме того, если не удается загрузить объявление, вы должны выйти и когда объявление загружается движение в

Для перемещения в использовании:.

[UIView beginAnimations:@"animateAdBannerOn" context:NULL]; 

// Assumes the banner view is just off the bottom of the screen. 

banner.frame = CGRectOffset(banner.frame, 0, banner.frame.size.height); 
     [UIView commitAnimations]; 

съехать использование:

[UIView beginAnimations:@"animateAdBannerOff" context:NULL]; 

// Assumes the banner view is placed at the bottom of the screen. 

banner.frame = CGRectOffset(banner.frame, 0, banner.frame.size.height); 
     [UIView commitAnimations]; 

You могут использовать уведомления для запуска этих методов. Также, когда пользователь купил «no-ad», выпустите уведомление об отключении. Также сохраните значение в NSUserdefaults, когда пользователь покупает «no-ad» и переводит метод в if-statement. И если пользователь купил «нет-объявления», он больше не хочет рекламировать рекламу.

P.S. Я бы использовал сеть посредничества объявлений, такую ​​как adMob или mopub, чтобы использовать несколько рекламных сетей и устанавливать приоритеты в прямом эфире вместо использования только iAd. iAd имеет очень низкую норму заполнения, по крайней мере, для большинства людей, особенно в некоторых странах. С большим количеством рекламных сетей вы можете достичь более высоких заполнений. Хорошим началом будет adMob + iAd, потому что adMob имеет действительно высокий фильтрат, и для меня, по крайней мере, они платят намного лучше. Я получаю доход от adMob 98%, а остальное - от iAd ... Также межстраничные объявления (полноэкранные) оплачиваются намного лучше, чем баннеры, и это очень просто реализовать. ;)

0

Я думаю, вы забыли установить нижнее ограничение на 0, когда объявление недоступно.

- (void)layoutAnimated:(BOOL)animated 
{ 
    CGRect contentFrame = self.view.bounds; 

    // all we need to do is ask the banner for a size that fits into the layout area we are using 
    CGSize sizeForBanner = [_bannerView sizeThatFits:contentFrame.size]; 

    // compute the ad banner frame 
    CGRect bannerFrame = _bannerView.frame; 
    if (_bannerView.bannerLoaded) { 

     // bring the ad into view 
     contentFrame.size.height -= sizeForBanner.height; // shrink down content frame to fit the banner below it 
     bannerFrame.origin.y = contentFrame.size.height; 
     bannerFrame.size.height = sizeForBanner.height; 
     bannerFrame.size.width = sizeForBanner.width; 

     // if the ad is available and loaded, shrink down the content frame to fit the banner below it, 
     // we do this by modifying the vertical bottom constraint constant to equal the banner's height 
     // 
     NSLayoutConstraint *verticalBottomConstraint = self.bottomConstraint; 
     verticalBottomConstraint.constant = sizeForBanner.height; 
     [self.view layoutSubviews]; 

    } else { 
     // hide the banner off screen further off the bottom 
     bannerFrame.origin.y = contentFrame.size.height; 
     NSLayoutConstraint *verticalBottomConstraint = self.bottomConstraint; 
     verticalBottomConstraint.constant = 0; 
     [self.view layoutSubviews]; 
    } 

    [UIView animateWithDuration:animated ? 0.25 : 0.0 animations:^{ 
     _contentView.frame = contentFrame; 
     [_contentView layoutIfNeeded]; 
     _bannerView.frame = bannerFrame; 
    }]; 
} 
Смежные вопросы