在套用 Google Admob 範例:
https://developers.google.com/admob/ios/banner
@import GoogleMobileAds;
@interface ViewController ()
@property(nonatomic, strong) GADBannerView *bannerView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// In this case, we instantiate the banner with desired ad size.
self.bannerView = [[GADBannerView alloc]
initWithAdSize:kGADAdSizeBanner];
[self addBannerViewToView:self.bannerView];
}
- (void)addBannerViewToView:(UIView *)bannerView {
bannerView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:bannerView];
[self.view addConstraints:@[
[NSLayoutConstraint constraintWithItem:bannerView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.bottomLayoutGuide
attribute:NSLayoutAttributeTop
multiplier:1
constant:0],
[NSLayoutConstraint constraintWithItem:bannerView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0]
]];
}
@end
結果顯示錯誤訊息:
NSLayoutConstraint for (null): Constraint must contain a first layout item
發生的原因是,直接套用了英文版裡的範例會出錯,改服用中文版裡的範例和指引就OK了。中文版的解法是:
https://developers.google.com/mobile-ads-sdk/docs/admob/ios/quick-start?hl=zh-tw
1:設定 Storyboard 裡的元件。
開啟 Main.storyboard
。在右下角的 Object library (物件程式庫)中,搜尋 UIView
,然後將 UIView
元素拖曳至檢視控制器。接著在右上角的 Identity inspector (身份偵測程式)中,將這個檢視設為自訂類別 GADBannerView
。
2:不需要 create object 進 GADBannerView,直接做 adUnitID assign 和 loadRequest.
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"Google Mobile Ads SDK version: %@", [GADRequest sdkVersion]);
self.bannerView.adUnitID = @"ca-app-pub-3940256099942544/2934735716";
self.bannerView.rootViewController = self;
[self.bannerView loadRequest:[GADRequest request]];
}