Banner Ads - cleveradssolutions/CAS-iOS GitHub Wiki

⚡ Before you start
Make sure you have correctly configure user consent flow.


Banner ads occupy a spot within an app's layout, either at the top or bottom of the device screen. They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. If you're new to mobile advertising, they're a great place to start.

This guide shows you how to integrate banner ads from CAS into an iOS app. Banner ads are displayed in CASBannerView objects, so the first step toward integrating banner ads is to include a CASBannerView in your view hierarchy. This is typically done either with the Interface Builder or programmatically.

AdSize

Size in points (WxH) Description Availability CASSize
320x50 Standard Banner Phones and Tablets banner
728x90 IAB Leaderboard Tablets leaderboard
300x250 IAB Medium Rectangle Phones and Tablets mediumRectangle
Adaptive Adaptive banner Phones and Tablets getAdaptiveBanner()
320x50 or 728x90 Smart Banner Phones and Tablets getSmartBanner()

❕Typically, Smart Banners on phones have a banner size. Or on tablets a leaderboard size.

adSize = CASSize.banner

Adaptive Banners

Adaptive banners are the next generation of responsive ads, maximizing performance by optimizing ad size for each device.
To pick the best ad size, adaptive banners use fixed aspect ratios instead of fixed heights. This results in banner ads that occupy a more consistent portion of the screen across devices and provide opportunities for improved performance.

  • The height of adaptive banners cannot be less than 50 points and more than 250 points.
  • The width of adaptive banners cannot be less than 300 points.
  • The adaptive banners use fixed aspect ratios instead of fixed heights.

Use the appropriate static methods on the ad size class, such as CASSize.getAdaptiveBanner to get an adaptive CASSize object.

// Get adaptive size in container view group:
adSize = CASSize.getAdaptiveBanner(inContainer: containerView)
// Get adaptive size in full screen width:
adSize = CASSize.getAdaptiveBanner(inWindow: containerWindow)
// Get adaptive size with width parameter:
adSize = CASSize.getAdaptiveBanner(forMaxWidth: maxWidth)

Warning

After changing the screen orientation, you should get the new adaptive ad size using the same method. And pass the size to the view. This will destroy the current ad content and load a new one.

Interface Builder

A CASBannerView 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 banner (320x50), use a width constraint of 320 points, and a height constraint of 50 points.

Create programmatically

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

Swift
class ViewController: UIViewController, CASBannerDelegate {
/* Class body ... */
    override func viewDidLoad() {
        super.viewDidLoad()
        // In this case, we instantiate the banner with desired ad size.
        bannerView = CASBannerView(adSize: adSize, manager: manager)      
        bannerView.setTranslatesAutoresizingMaskIntoConstraints = false
        // This view controller is used to present an overlay when the ad is clicked. 
        bannerView.rootViewController = self
        addBannerViewToView(bannerView) // Read below
    }
}
Objective-C
@implementation ViewController
/* Class body ... */
- (void)viewDidLoad {
    [super viewDidLoad];
        // In this case, we instantiate the banner with desired ad size.
        self.bannerView = [[CASBannerView alloc] initWithAdSizeCASSize.banner manager:manager];        
        [self.bannerView setTranslatesAutoresizingMaskIntoConstraints:NO];
        // This view controller is used to present an overlay when the ad is clicked. 
        self.bannerView.rootViewController = self; // Weak reference
        [self.addBannerViewToView:self.bannerView]; // Read below
    }
}

Ad events

To further customize the behavior of your ad, you can hook onto a number of events in the ad's lifecycle: loading, presenting, clicking, and so on. You can listen for these events through the CASBannerDelegate protocol.
To use an CASBannerDelegate with Banner View, call the adDelegate property:

override func viewDidLoad() {
  super.viewDidLoad()
  // Create or get Banner View
  bannerView.adDelegate = self
}

func bannerAdViewDidLoad(_ view: CASBannerView){
  // Invokes this callback when ad loaded and ready to present.
}

func bannerAdView(_ adView: CASBannerView, didFailWith error: CASError){
  // Invokes this callback when an error occurred with the ad.
  // - To see a description of the error, see `CASError.message`.
}

func bannerAdView(_ adView: CASBannerView, willPresent impression: CASImpression){
  // Invokes this callback when the ad will presenting for user with info about the impression.
}

func bannerAdViewDidRecordClick(_ adView: CASBannerView){
  // Invokes this callback when a user clicks the ad.
}

Warning

Keep in mind that the reference to the adDelegate will be weak and may be removed from memory.

Note

Read more about event bannerAdView(_:willPresent:) with Impression Metadata.

Autoload Banner Ad

A isAutoloadEnabled value that determines whether autoloading of ads in the receiver is enabled.
If enabled, you do not need to call the loadNextAd() method from next section to load ads.
Change the banner autoload ad using the following method:

bannerView.isAutoloadEnabled = true

By default enabled if global state is NOT CASSettings.setLoading(mode: LoadingManagerMode.Manual).
And changes will override global state of CASSettings.setLoading(mode:) for specific Banner View.

Load Banner Ad

You can use load regardless of the isAutoloadEnabled value for interrupt ad impression and load next ad..

bannerView.loadNextAd();

Warning

Calling the loadNextAd() method if isAutoloadEnabled is active will cause the current ad to be lost and a new ad to start loading.

Banner refresh rate

An ad unit’s automatic refresh rate determines how often a new ad request is generated for that ad unit.
We recommended using refresh rate 30 seconds. However, you can choose any value you want longer than 10 seconds.

Change the banner automatic refresh rate using the following method:

bannerView.refreshInterval = interval
// OR disable auto refresh ads
bannerView.disableAdRefresh()

Note

  • Ad requests should not be made when the device screen is turned off.
  • The isAutoloadEnabled has no effect on refreshing the banner ad.

Check the ad availability

You can ask for the ad availability directly by calling the following function:

adLoaded = bannerView.isAdReady

Banner Ad visibility

The banner is a normal view so you can feel free to change the visibility with the following method:

bannerView.isHidden = true

Free Ad memory

If you no longer need the bannerView, please call Destroy to free memory.

override func viewDidDisappear(){
  super.viewDidDisappear()
  bannerView.destroy()
}

Safe Area

Banner ads must be placed in the "Safe Area" to avoid being obscured by rounded corners, sensor housing, and the Home indicator.

Storyboard/Interface Builder

If your app uses Interface Builder, first, ensure you have enabled Safe Area layout guides. To do this you need:

  • Open your Interface Builder file.
  • Click on your view controller scene .
  • You will see the Interface Builder Document options on the right.
  • Check Use Safe Area Layout Guides.

If you wish to have a left- or right-aligned banner, constrain the left/right edge of the banner to the left/right edge of the safe area and not the left/right edge of the superview.

If you have Use Safe Area Layout Guides enabled, interface builder will default to using the safe area edges when adding constraints to the view.

Programmatic

If your app creates banner ads programmatically, you can define constraints and position the banner ad in code. This example shows how to constrain a banner to be centered horizontally at the bottom of the Safe Area:

Swift
func addBannerViewToView(_ bannerView: UIView) {
    bannerView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(bannerView)
    if #available(iOS 11.0, *) {
      positionBannerAtBottomOfSafeArea(bannerView)
    }
    else {
      positionBannerAtBottomOfView(bannerView)
    }
}

@available (iOS 11, *)
func positionBannerAtBottomOfSafeArea(_ bannerView: UIView) {
    // Position the banner. Stick it to the bottom of the Safe Area.
    // Centered horizontally.
    let guide: UILayoutGuide = view.safeAreaLayoutGuide

    NSLayoutConstraint.activate(
      [bannerView.centerXAnchor.constraint(equalTo: guide.centerXAnchor),
       bannerView.bottomAnchor.constraint(equalTo: guide.bottomAnchor)]
    )
}

func positionBannerAtBottomOfView(_ bannerView: UIView) {
    // Center the banner horizontally.
    view.addConstraint(NSLayoutConstraint(item: bannerView,
                                          attribute: .centerX,
                                          relatedBy: .equal,
                                          toItem: view,
                                          attribute: .centerX,
                                          multiplier: 1,
                                          constant: 0))
    // Lock the banner to the top of the bottom layout guide.
    view.addConstraint(NSLayoutConstraint(item: bannerView,
                                          attribute: .bottom,
                                          relatedBy: .equal,
                                          toItem: self.bottomLayoutGuide,
                                          attribute: .top,
                                          multiplier: 1,
                                          constant: 0))
}
Objective-C
-(void)addBannerViewToView:(UIView *_Nonnull)bannerView {
  self.bannerView.translatesAutoresizingMaskIntoConstraints = NO;
  [self.view addSubview:self.bannerView];
  if (@available(ios 11.0, *)) {
    [self positionBannerViewAtBottomOfSafeArea:bannerView];
  } else {
    [self positionBannerViewAtBottomOfView:bannerView];
  }
}

- (void)positionBannerViewAtBottomOfSafeArea:(UIView *_Nonnull)bannerView NS_AVAILABLE_IOS(11.0) {
  // Position the banner. Stick it to the bottom of the Safe Area.
  // Centered horizontally.
  UILayoutGuide *guide = self.view.safeAreaLayoutGuide;
  [NSLayoutConstraint activateConstraints:@[
    [bannerView.centerXAnchor constraintEqualToAnchor:guide.centerXAnchor],
    [bannerView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor]
  ]];
}

- (void)positionBannerViewAtBottomOfView:(UIView *_Nonnull)bannerView {
  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
                                                        attribute:NSLayoutAttributeCenterX
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.view
                                                        attribute:NSLayoutAttributeCenterX
                                                       multiplier:1
                                                         constant:0]];
  [self.view addConstraint:[NSLayoutConstraint constraintWithItem:bannerView
                                                        attribute:NSLayoutAttributeBottom
                                                        relatedBy:NSLayoutRelationEqual
                                                           toItem:self.bottomLayoutGuide
                                                        attribute:NSLayoutAttributeTop
                                                       multiplier:1
                                                         constant:0]];
}

The techniques above can easily be used for constraining to the top of the safe area by modifying the attributes and anchors used.


🔗 Done! What’s Next?

⚠️ **GitHub.com Fallback** ⚠️