admob 广告代码参考 iOS banner广告

文章目录

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.

项目交流联系微信:toushouapp-com,或验证加交流QQ群:595990939,添加需告知来意。

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

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

关注微信公众号

微信公众号
toushouappcom

扫码入群

微信扫一扫
长按识别入群

QQ扫描加群

QQ扫描加群
595990939


投手网-优化师-教程 » admob 广告代码参考 iOS banner广告

扫码,关注更多行业内容
微信二维码
APP产品投放无服务费
QQ二维码
微信号:
QQ号:
复制文字

toushouapp-com

复制文字

2109763290