admob 广告代码参考 iOS banner广告
- lways test with test ads
- Create a GADBannerView
- Configure GADBannerView properties
- Load an ad
- Ad events
- Registering for banner events
- SWIFT
- OBJECTIVE-C
- Implementing banner events
- SWIFT
- OBJECTIVE-C
- Use cases
- SWIFT
- OBJECTIVE-C
- SWIFT
- OBJECTIVE-C
- Banner sizes
- Smart Banners
- Additional resources
- Next steps
lways test with test ads
When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.
The easiest way to load test ads is to use our dedicated test ad unit ID for iOS banners: ca-app-pub-3940256099942544/2934735716

使用微信扫描二维码关注公众号后,回复“查看码”获取查看码
rootViewController
- This view controller is used to present an overlay when the ad is clicked. It should normally be set to the view controller that contains theGADBannerView
.adUnitID
- This is the AdMob ad unit ID from which theGADBannerView
should load ads.
Here's a code example showing how to set the two required properties in the viewDidLoad
method of a UIViewController:
- (void)viewDidLoad {
[super viewDidLoad];
...
self.bannerView.adUnitID = @"ca-app-pub-3940256099942544/2934735716";
self.bannerView.rootViewController = self;
}
Note:
Ad unit IDs are created in the AdMob UI, and represent a place in your app where ads appear. If you show banner ads in two view controllers, for example, you can create an ad unit for each one.
Load an ad
Once the GADBannerView
is in place and its properties configured, it's time to load an ad. This is done by calling loadRequest:
on a GADRequest
object:
- (void)viewDidLoad {
[super viewDidLoad];
...
self.bannerView.adUnitID = @"ca-app-pub-3940256099942544/2934735716";
self.bannerView.rootViewController = self;
[self.bannerView loadRequest:[GADRequest request]];
}
GADRequest objects represent a single ad request, and contain properties for things like targeting information.
Ad events
Through the use of GADBannerViewDelegate
, you can listen for lifecycle events, such as when an ad is closed or the user leaves the app.
Registering for banner events
To register for banner ad events, set the delegate
property on GADBannerView
to an object that implements the GADBannerViewDelegate
protocol. Generally, the class that implements banner ads also acts as the delegate class, in which case, the delegate
property can be set to self
.
@import GoogleMobileAds;
@interface ViewController () <GADBannerViewDelegate>
@property(nonatomic, strong) GADBannerView *bannerView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
...
self.bannerView.delegate = self;
}
Implementing banner events
Each of the methods in GADBannerViewDelegate
is marked as optional, so you only need to implement the methods you want. This example implements each method and logs a message to the console:
/// Tells the delegate an ad request loaded an ad.
- (void)adViewDidReceiveAd:(GADBannerView *)adView {
NSLog(@"adViewDidReceiveAd");
}
/// Tells the delegate an ad request failed.
- (void)adView:(GADBannerView *)adView
didFailToReceiveAdWithError:(GADRequestError *)error {
NSLog(@"adView:didFailToReceiveAdWithError: %@", [error localizedDescription]);
}
/// Tells the delegate that a full-screen view will be presented in response
/// to the user clicking on an ad.
- (void)adViewWillPresentScreen:(GADBannerView *)adView {
NSLog(@"adViewWillPresentScreen");
}
/// Tells the delegate that the full-screen view will be dismissed.
- (void)adViewWillDismissScreen:(GADBannerView *)adView {
NSLog(@"adViewWillDismissScreen");
}
/// Tells the delegate that the full-screen view has been dismissed.
- (void)adViewDidDismissScreen:(GADBannerView *)adView {
NSLog(@"adViewDidDismissScreen");
}
/// Tells the delegate that a user click will open another app (such as
/// the App Store), backgrounding the current app.
- (void)adViewWillLeaveApplication:(GADBannerView *)adView {
NSLog(@"adViewWillLeaveApplication");
}
See the Ad Delegate example for an implementation of banner delegate methods in the iOS API Demo app.
SWIFT OBJECTIVE-C
Use cases
Here are some example use cases for these ad event methods.
Adding a banner to the view hierarchy once an ad is received
You may want to delay in adding a GADBannerView
to the view hierarchy until after an ad is received. You can do this by listening for the adViewDidReceiveAd:
event:
- (void)adViewDidReceiveAd:(GADBannerView *)adView {
// Add adView to view and add constraints as above.
[self addBannerViewToView:bannerView];
}
Animating a banner ad
You can also use the adViewDidReceiveAd:
event to animate a banner ad once it's returned, as shown in the following example:
- (void)adViewDidReceiveAd:(GADBannerView *)adView {
adView.alpha = 0;
[UIView animateWithDuration:1.0 animations:^{
adView.alpha = 1;
}];
}
Third-party analytics
The SDK automatically tracks clicks and impressions, but if you're also using a third-party analytics solution, you can track each of the GADBannerViewDelegate
calls separately.
Pausing and resuming the app
The GADBannerViewDelegate
protocol has methods to notify you of events, such as when a click causes an overlay to be presented or dismissed, or invokes an external browser. If you want to trace whether these events were due to ads, register for these GADBannerViewDelegate
methods.
To catch all types of overlay presentations or external browser invocations, not just those that come from ad clicks, your app is better off listening for the equivalent methods on UIViewController
or UIApplication
. Here is a table showing the equivalent iOS methods that are invoked at the same time as GADBannerViewDelegate
methods:
GADBannerViewDelegate method | iOS method |
---|---|
adViewWillPresentScreen: |
UIViewController's viewWillDisappear: |
adViewWillDismissScreen: |
UIViewController's viewWillAppear: |
adViewDidDismissScreen: |
UIViewController's viewDidAppear: |
adViewWillLeaveApplication: |
UIApplicationDelegate's applicationDidEnterBackground: |
Banner sizes
The table below lists the supported banner sizes.
Size in points (WxH) | Description | Availability | AdSize constant |
---|---|---|---|
320x50 | Standard banner | Phones and tablets | kGADAdSizeBanner |
320x100 | Large banner | Phones and tablets | kGADAdSizeLargeBanner |
300x250 | IAB medium rectangle | Phones and tablets | kGADAdSizeMediumRectangle |
468x60 | IAB full-size banner | Tablets | kGADAdSizeFullBanner |
728x90 | IAB leaderboard | Tablets | kGADAdSizeLeaderboard |
Screen width x 32|50|90 | Smart banner | Phones and tablets | kGADAdSizeSmartBannerPortrait kGADAdSizeSmartBannerLandscape |
Smart Banners
Smart Banners are ad units that render screen-width banner ads on any screen size across different devices in either orientation. Smart Banners help deal with increasing screen fragmentation across different devices by "smartly" detecting the width of the device in its current orientation and making the ad view that size.
Smart Banners on iPhones have a height of 50 points in portrait and 32 points in landscape. On iPads, height is 90 points in both portrait and landscape.
When an image ad isn't large enough to take up the entire allotted space, the image will be centered, and the space on either side will be filled in.
To use Smart Banners, just specify kGADAdSizeSmartBannerPortrait
(for portait orientation) or kGADAdSizeSmartBannerLandscape
(for landscape orientation) for the ad size:
GADBannerView *bannerView = [[GADBannerView alloc]
initWithAdSize:kGADAdSizeSmartBannerPortrait];
Since the addition of the safe area for iOS 11, for full-width banners you should also add constraints for the edges of the banner to the edges of the safe area. Here is a code snippet showing how to do this:
- (void)addBannerViewToView:(UIView *)bannerView {
bannerView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:bannerView];
if (@available(ios 11.0, *)) {
// In iOS 11, we need to constrain the view to the safe area.
[self positionBannerViewFullWidthAtBottomOfSafeArea:bannerView];
} else {
// In lower iOS versions, safe area is not available so we use
// bottom layout guide and view edges.
[self positionBannerViewFullWidthAtBottomOfView:bannerView];
}
}
#pragma mark - view positioning
- (void)positionBannerViewFullWidthAtBottomOfSafeArea:(UIView *_Nonnull)bannerView NS_AVAILABLE_IOS(11.0) {
// Position the banner. Stick it to the bottom of the Safe Area.
// Make it constrained to the edges of the safe area.
UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
[NSLayoutConstraint activateConstraints:@[
[guide.leftAnchor constraintEqualToAnchor:bannerView.leftAnchor],
[guide.rightAnchor constraintEqualToAnchor:bannerView.rightAnchor],
[guide.bottomAnchor constraintEqualToAnchor:bannerView.bottomAnchor]
]];
}
- (void)positionBannerViewFullWidthAtBottomOfView:(UIView *_Nonnull)bannerView {
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeading
multiplier:1
constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.bottomLayoutGuide
attribute:NSLayoutAttributeTop
multiplier:1
constant:0]];
}
Additional resources
Samples on GitHub
-
Banner ads example: Swift | Objective-C
-
Advanced features demo: Swift | Objective-C
Mobile Ads Garage video tutorials
- Banner Implementation
- Banner Best Practices
Next steps
- If you haven't already, create your own app and banner ad unit in the AdMob UI and use your newly created app ID and ad unit ID in your code. Remember to configure your device with test ads.
- Learn about ad targeting and banner ad guidance.
- Try another ad format:
- Interstitial
- Rewarded Video
- Native