admob 广告代码参考 iOS banner广告

来源:互联网 发布:手机淘宝兼职青青岛 编辑:程序博客网 时间:2024/05/01 19:48

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

It's been specially configured to return test ads for every request, and you're free to use it in your own apps while coding, testing, and debugging. Just make sure you replace it with your own ad unit ID before publishing your app.

For more information about how the Mobile Ads SDK's test ads work, see Test Ads.

Create a GADBannerView

Banner ads are displayed in GADBannerView objects, so the first step toward integrating banner ads is to include a GADBannerView in your view hierarchy. This is typically done in one of two ways.

Interface Builder

GADBannerView can be added to a storyboard or xib file like any typical view. When using this method, be sure to add width and height constraints to match the ad size you'd like to display. For example, when displaying a standard banner (320x50), use a width constraint of 320 points, and a height constraint of 50 points.

Programmatically

GADBannerView can also be instantiated directly. Here's an example of how to create a GADBannerView, aligned to the bottom center of the safe area of the screen, with the standard banner size of 320x50:

SWIFT

OBJECTIVE-C

@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: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

Note that in this case we don't give width or height constraints, as the provided ad size will give the banner an intrinsic content size to size the view.

Configure GADBannerView properties

In order to load and display ads, GADBannerView requires a few properties be set.

  • 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 the GADBannerView.
  • adUnitID - This is the AdMob ad unit ID from which the GADBannerView should load ads.

Here's a code example showing how to set the two required properties in the viewDidLoadmethod of a UIViewController:

SWIFT

OBJECTIVE-C

- (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:

SWIFT

OBJECTIVE-C

- (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.

SWIFT

OBJECTIVE-C

@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:

SWIFT

OBJECTIVE-C

/// 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:

SWIFT

OBJECTIVE-C

- (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:

SWIFT

OBJECTIVE-C

- (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 GADBannerViewDelegatemethods.

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 methodiOS methodadViewWillPresentScreen: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)DescriptionAvailabilityAdSize constant320x50Standard bannerPhones and tabletskGADAdSizeBanner320x100Large bannerPhones and tabletskGADAdSizeLargeBanner300x250IAB medium rectanglePhones and tabletskGADAdSizeMediumRectangle468x60IAB full-size bannerTabletskGADAdSizeFullBanner728x90IAB leaderboardTabletskGADAdSizeLeaderboardScreen width x 32|50|90Smart bannerPhones and tabletskGADAdSizeSmartBannerPortrait
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:

SWIFT

OBJECTIVE-C

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:

SWIFT

OBJECTIVE-C

- (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
原创粉丝点击