Native Ads (Unified) - Custom Rendering

Native ads are ad assets that are presented to users via UI components that are native to the platform. They're shown using the same classes you already use in your storyboards, and can be formatted to match your app's visual design. When an ad loads, your app receives an ad object that contains its assets, and the app (rather than the SDK) is then responsible for displaying them.

This guide will show you how to use the Google Mobile Ads SDK to implement native ads in an iOS application, as well as some important things to consider along the way.

Prerequisites

This guide assumes some working knowledge of the Google Mobile Ads SDK, so if you haven't already, consider running through our Get Started guide.

Always test with test ads

Before you begin, remember that when building and testing your apps, you should be sure that you're using test ads rather than live, production ads. Testing with production ads could lead to suspension of your account.

The easiest way to load test ads is to use our dedicated test ad unit ID for all native advanced ads on iOS:

/6499/example/native

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.

Loading ads

There are two system-defined formats for native ads: app install and content.

Both types of ads are represented by one class: GADUnifiedNativeAd. An instance of this class contains the assets for the native ad. Note that depending on the type of ad represented by the GADUnifiedNativeAd, some fields will not be populated (i.e., they will be nil).

Native ads are loaded via GADAdLoader objects, which send messages to their delegates according to the GADAdLoaderDelegate protocol.

In addition to the system-defined native formats, Google Ad Manager publishers have the option of creating their own native ad formats by defining custom lists of assets. These are called custom native ad formats, and can be used for direct-sold native ads. Custom native ad formats enable publishers to pass arbitrary structured data to their apps. These ads are represented by the GADNativeCustomTemplateAd class.

Custom native ad formats are also referred to as custom template ads because publishers define their own "templates" (lists of asset names and types) for their custom native ad formats. Custom native ads and custom template ads are the same kind of ad.

Initialize the ad loader

Before you can load an ad, you have to initialize the ad loader. The following code demonstrates how to initialize a GADAdLoader:

Swift

adLoader = GADAdLoader(adUnitID: "/6499/example/native",
    rootViewController: self,
    adTypes: [ kGADAdLoaderAdTypeUnifiedNative ],
    options: [ ... ad loader options objects ... ])
adLoader.delegate = self

Objective-C

self.adLoader = [[GADAdLoader alloc]
      initWithAdUnitID:@"/6499/example/native"
    rootViewController:rootViewController
               adTypes:@[ ... ad type constants ... ]
               options:@[ ... ad loader options objects ... ]];
self.adLoader.delegate = self;

You'll need an ad unit ID (you can use the test ID), constants to pass in the adTypes array to specify which native formats you want to request, and any options you wish to set in the options parameter. The list of possible values for the options parameter can be found below in the Setting native ad options section.

The adTypes array should contain one or more of the following constants:

Implement the ad loader delegate

The ad loader delegate needs to implement protocols specific your ad type. For unified native ads:

  • GADUnifiedNativeAdLoaderDelegate This protocol includes a message that's sent to the delegate when a unified native ad has loaded:

    Swift

    public func adLoader(_ adLoader: GADAdLoader,
        didReceive nativeAd: GADUnifiedNativeAd)
    

    Objective-C

    - (void)adLoader:(GADAdLoader *)adLoader
        didReceiveNativeAd:(GADUnifiedNativeAd *)nativeAd;
    
  • GADNativeCustomTemplateAdLoaderDelegate. This protocol includes a message that's sent to the delegate when a custom template ad has loaded:

    Swift

    func adLoader(_ adLoader: GADAdLoader,
                    didReceive nativeCustomTemplateAd: GADNativeCustomTemplateAd)
    

    Objective-C

    - (void)adLoader:(GADAdLoader *)adLoader
        didReceiveNativeCustomTemplateAd:(GADNativeCustomTemplateAd *) nativeCustomTemplateAd;
    

Request the ad

Once your GADAdLoader is initialized, call its loadRequest: method to request an ad:

Swift

adLoader.load(DFPRequest())

Objective-C

[self.adLoader loadRequest:[DFPRequest request]];

The loadRequest: method in GADAdLoader accepts the same DFPRequest objects as banners and interstitials. You can use request objects to add targeting information, just as you would with other ad types.

A single GADAdLoader can make multiple requests, but only if they're done one at a time. When reusing a GADAdLoader, make sure you wait for each request to finish before calling loadRequest: again to begin the next. If you need to request multiple ads in parallel, you can always use multiple GADAdLoader objects.

When to request ads

Apps displaying native ads are free to request them in advance of when they'll actually be displayed. In many cases, this is the recommended practice. An app displaying a list of items with native ads mixed in, for example, can load native ads for the whole list, knowing that some will be shown only after the user scrolls the view and some may not be displayed at all.

While prefetching ads is a great technique, it's important that you don't keep old ads around forever without displaying them. Any native ad objects that have been held without display for longer than an hour should be discarded and replaced with new ads from a new request.

Handling failed requests

The above protocols extend the GADAdLoaderDelegate protocol, which defines a message sent when ads fail to load. You can use the GADRequestError object to determine the cause of the error.

Swift

public func adLoader(_ adLoader: GADAdLoader,
    didFailToReceiveAdWithError error: GADRequestError)

Objective-C

- (void)adLoader:(GADAdLoader *)adLoader
    didFailToReceiveAdWithError:(GADRequestError *)error;

Get notified of native ad events

To be notified of events related to the native ad interactions, set the delegate property of the native ad:

Swift

nativeAd.delegate = self

Objective-C

nativeAd.delegate = self;

Then implement GADUnifiedNativeAdDelegate to receive the following delegate calls:

Swift

func nativeAdDidRecordImpression(_ nativeAd: GADUnifiedNativeAd) {
  // The native ad was shown.
}

func nativeAdDidRecordClick(_ nativeAd: GADUnifiedNativeAd) {
  // The native ad was clicked on.
}

func nativeAdWillPresentScreen(_ nativeAd: GADUnifiedNativeAd) {
  // The native ad will present a full screen view.
}

func nativeAdWillDismissScreen(_ nativeAd: GADUnifiedNativeAd) {
  // The native ad will dismiss a full screen view.
}

func nativeAdDidDismissScreen(_ nativeAd: GADUnifiedNativeAd) {
  // The native ad did dismiss a full screen view.
}

func nativeAdWillLeaveApplication(_ nativeAd: GADUnifiedNativeAd) {
  // The native ad will cause the application to become inactive and
  // open a new application.
}

Objective-C

- (void)nativeAdDidRecordImpression:(GADUnifiedNativeAd *)nativeAd {
  // The native ad was shown.
}

- (void)nativeAdDidRecordClick:(GADUnifiedNativeAd *)nativeAd {
  // The native ad was clicked on.
}

- (void)nativeAdWillPresentScreen:(GADUnifiedNativeAd *)nativeAd {
  // The native ad will present a full screen view.
}

- (void)nativeAdWillDismissScreen:(GADUnifiedNativeAd *)nativeAd {
  // The native ad will dismiss a full screen view.
}

- (void)nativeAdDidDismissScreen:(GADUnifiedNativeAd *)nativeAd {
  // The native ad did dismiss a full screen view.
}

- (void)nativeAdWillLeaveApplication:(GADUnifiedNativeAd *)nativeAd {
  // The native ad will cause the application to become inactive and
  // open a new application.
}

Native ad options

The last parameter included in the creation of the GADAdLoader above is an optional array of objects.

Swift

adLoader = GADAdLoader(adUnitID: "/6499/example/native",
    rootViewController: self,
    adTypes: [ ... ad type constants ... ],
    options: [ ... ad loader options objects ... ])

Objective-C

self.adLoader = [[GADAdLoader alloc]
      initWithAdUnitID:@"/6499/example/native"
    rootViewController:rootViewController
               adTypes:@[ ... ad type constants ... ]
               options:@[ ... ad loader options objects ... ]];

This optional array holds one or more instances of a GADAdLoaderOptions subclass (GADNativeAdImageAdLoaderOptions), which are objects that an app can use to indicate its preferences for how native ads should be loaded and behave.

GADNativeAdImageAdLoaderOptions contains properties relating to images in Native Advanced ads. Apps can control how a GADAdLoader handles Native Ads Advanced image assets by creating a GADNativeAdImageAdLoaderOptions object, setting its properties (disableImageLoading, preferredImageOrientation, and shouldRequestMultipleImages), and passing it in during initialization.

GADNativeAdImageAdLoaderOptions has the following properties:

disableImageLoading
Image assets for native ads are returned via instances of GADNativeAdImage, which contains image and imageURL properties. If disableImageLoading is set to false, which is the default (NO in Objective-C), the SDK will fetch image assets automatically and populate both the image and the imageURL properties for you. If it's set to true (or YES in Objective-C), the SDK will only populate imageURL, allowing you to download the actual images at your discretion.
preferredImageOrientation

Some creatives have multiple images available to match different device orientations. Apps can request images for a particular orientation by setting this property to one of the orientation constants:

  • GADNativeAdImageAdLoaderOptionsOrientationAny
  • GADNativeAdImageAdLoaderOptionsOrientationLandscape
  • GADNativeAdImageAdLoaderOptionsOrientationPortrait

    If you use preferredImageOrientation to specify a preference for landscape or portrait image orientation, the SDK will place images matching that orientation first in image asset arrays and place non-matching images after them. Since some ads will only have one orientation available, publishers should make sure that their apps can handle both landscape and portrait images.

    If this method is not called, the default value of GADNativeAdImageAdLoaderOptionsOrientationAny will be used.

shouldRequestMultipleImages

Some image assets will contain a series of images rather than just one. By setting this value to true, your app indicates that it's prepared to display all the images for any assets that have more than one. By setting it to false (the default) your app instructs the SDK to provide just the first image for any assets that contain a series.

If no GADAdLoaderOptions objects are passed in when initializing a GADAdLoader, the default value for each option will be used.

GADNativeAdViewOptions

GADNativeAdViewAdOptions objects are used to indicate preferences for how native ad views should represent ads. They have a single property: preferredAdChoicesPosition, which you can use to specify the location where the AdChoices icon should be placed. The icon can appear at any corner of the ad, and defaults to GADAdChoicesPositionTopRightCorner. The possible values for this property are:

  • GADAdChoicesPositionTopRightCorner
  • GADAdChoicesPositionTopLeftCorner
  • GADAdChoicesPositionBottomRightCorner
  • GADAdChoicesPositionBottomLeftCorner

Here's an example showing how to place the AdChoices icon in the top left corner of an ad:

Swift

let adViewOptions = GADNativeAdViewAdOptions()
adViewOptions.preferredAdChoicesPosition = .topLeftCorner
adLoader = GADAdLoader(adUnitID: "/6499/example/native",
    rootViewController: self,
    adTypes: [ ... ad type constants ... ],
    options: [ ... ad loader options objects ... ])

Objective-C

GADNativeAdViewAdOptions *adViewOptions = [[GADNativeAdViewAdOptions alloc] init];
adViewOptions.preferredAdChoicesPosition = GADAdChoicesPositionTopLeftCorner;
self.adLoader = [[GADAdLoader alloc]
      initWithAdUnitID:@"/6499/example/native"
    rootViewController:self
               adTypes:@[ ... ad type constants ...  ]
               options:@[ ... ad loader options objects ... ]];

GADVideoOptions

GADVideoOptions objects are used to indicate how native video assets should be displayed. They offer a single property: startMuted.

This boolean indicates whether video assets should begin playback in a muted state. The default value is true.

Displaying a system-defined native ad format

When a native ad loads, your app will receive a native ad object via one of the GADAdLoaderDelegate protocol messages. Your app is then responsible for displaying the ad (though it doesn't necessarily have to do so immediately). To make displaying system-defined ad formats easier, the SDK offers some useful resources.

GADUnifiedNativeAdView

For the GADUnifiedNativeAd, there is a corresponding "ad view" class: GADUnifiedNativeAdView. This ad view class is a UIView that publishers should use to display the ad. A single GADUnifiedNativeAdView, for example, can display a single instance of a GADUnifiedNativeAd. Each of the UIView objects used to display that ad's assets should be subviews of that GADUnifiedNativeAdView object.

If you were displaying an ad in a UITableView, for example, the view hierarchy for one of the cells might look like this:

The GADUnifiedNativeAdView class also provides IBOutlets used to register the view used for each individual asset, and a method to register the GADUnifiedNativeAd object itself. Registering the views in this way allows the SDK to automatically handle tasks such as:

  • Recording clicks.
  • Recording impressions (when the first pixel is visible on the screen).
  • Displaying the AdChoices overlay.

The AdChoices overlay

For indirect native ads (delivered via Ad Manager backfill or through Ad Exchange or AdSense), an AdChoices overlay is added by the SDK. Please leave space in your preferred corner of your native ad view for the automatically inserted AdChoices logo. Also, make sure the AdChoices overlay is placed on content that allows the icon to be easily seen. For more information on the overlay's appearance and function, see the programmatic native ads implementation guidelines.

Ad attribution for programmatic native ads

When displaying programmatic native ads, you must display an ad attribution to denote that the view is an advertisement. See this page for the policy guidelines.

Code example

Let's take a look at how to display native ads using views loaded dynamically from xib files. This can be a very useful approach when using GADAdLoaders configured to request multiple formats.

Laying out the UIViews

The first step is to lay out the UIViews that will display native ad assets. You can do this in the Interface Builder as you would when creating any other xib file. Here's how the layout for a native ad might look:

Note the Custom Class value in the top right of the image. It's set to GADUnifiedNativeAdView. This is the ad view class that is used to display a GADUnifiedNativeAd.

You'll also need to set the custom class for the GADMediaView, which is used to display the video or image for the ad.

Linking outlets to views

Once the views are in place and you've assigned the correct ad view class to the layout, link the ad view's asset outlets to the UIViews you've created. Here's how you might link the ad view's asset outlets to the UIViews created for an ad: In the outlet panel, the outlets in GADUnifiedNativeAdView have been linked to the UIViews laid out in the Interface Builder. This lets the SDK know which UIView displays which asset. It's also important to remember that these outlets represent the views that are clickable in the ad.

Displaying the ad

Once the layout is complete and the outlets are linked, the last step is to add code to your app that displays an ad once it has loaded. Here's a method to display an ad in the view defined above:

Swift

// Mark: - GADUnifiedNativeAdLoaderDelegate
func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADUnifiedNativeAd) {
  print("Received unified native ad: \(nativeAd)")
  refreshAdButton.isEnabled = true
  // Create and place ad in view hierarchy.
  let nibView = Bundle.main.loadNibNamed("UnifiedNativeAdView", owner: nil, options: nil)?.first
  guard let nativeAdView = nibView as? GADUnifiedNativeAdView else {
    return
  }
  setAdView(nativeAdView)

  // Associate the native ad view with the native ad object. This is
  // required to make the ad clickable as well as populate the media view.
  nativeAdView.nativeAd = nativeAd

  // Populate the native ad view with the native ad assets.
  // The headline is guaranteed to be present in every native ad.
  (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline

  // These assets are not guaranteed to be present. Check that they are before
  // showing or hiding them.
  (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body
  nativeAdView.bodyView?.isHidden = nativeAd.body == nil

  (nativeAdView.callToActionView as? UIButton)?.setTitle(nativeAd.callToAction, for: .normal)
  nativeAdView.callToActionView?.isHidden = nativeAd.callToAction == nil

  (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image
  nativeAdView.iconView?.isHidden = nativeAd.icon == nil

  (nativeAdView.starRatingView as? UIImageView)?.image = imageOfStars(fromStarRating:nativeAd.starRating)
  nativeAdView.starRatingView?.isHidden = nativeAd.starRating == nil

  (nativeAdView.storeView as? UILabel)?.text = nativeAd.store
  nativeAdView.storeView?.isHidden = nativeAd.store == nil

  (nativeAdView.priceView as? UILabel)?.text = nativeAd.price
  nativeAdView.priceView?.isHidden = nativeAd.price == nil

  (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser
  nativeAdView.advertiserView?.isHidden = nativeAd.advertiser == nil

  // In order for the SDK to process touch events properly, user interaction
  // should be disabled.
  nativeAdView.callToActionView?.isUserInteractionEnabled = false
}

Objective-C

#pragma mark GADUnifiedNativeAdLoaderDelegate implementation

- (void)adLoader:(GADAdLoader *)adLoader didReceiveUnifiedNativeAd:(GADUnifiedNativeAd *)nativeAd {
  NSLog(@"Received unified native ad: %@", nativeAd);
  self.refreshButton.enabled = YES;

  // Create and place ad in view hierarchy.
  GADUnifiedNativeAdView *nativeAdView =
      [[NSBundle mainBundle] loadNibNamed:@"UnifiedNativeAdView" owner:nil options:nil].firstObject;
  [self setAdView:nativeAdView];

  // Associate the native ad view with the native ad object. This is
  // required to make the ad clickable as well as populate the media view.
  nativeAdView.nativeAd = nativeAd;

  // Populate the native ad view with the native ad assets.
  // The headline is guaranteed to be present in every native ad.
  ((UILabel *)nativeAdView.headlineView).text = nativeAd.headline;

  // These assets are not guaranteed to be present. Check that they are before
  // showing or hiding them.
  ((UILabel *)nativeAdView.bodyView).text = nativeAd.body;
  nativeAdView.bodyView.hidden = nativeAd.body ? NO : YES;

  [((UIButton *)nativeAdView.callToActionView)setTitle:nativeAd.callToAction
                                              forState:UIControlStateNormal];
  nativeAdView.callToActionView.hidden = nativeAd.callToAction ? NO : YES;

    ((UIImageView *)nativeAdView.iconView).image = nativeAd.icon.image;
  nativeAdView.iconView.hidden = nativeAd.icon ? NO : YES;

  ((UIImageView *)nativeAdView.starRatingView).image = [self imageForStars:nativeAd.starRating];
  nativeAdView.starRatingView.hidden = nativeAd.starRating ? NO : YES;

  ((UILabel *)nativeAdView.storeView).text = nativeAd.store;
  nativeAdView.storeView.hidden = nativeAd.store ? NO : YES;

  ((UILabel *)nativeAdView.priceView).text = nativeAd.price;
  nativeAdView.priceView.hidden = nativeAd.price ? NO : YES;

  ((UILabel *)nativeAdView.advertiserView).text = nativeAd.advertiser;
  nativeAdView.advertiserView.hidden = nativeAd.advertiser ? NO : YES;

  // In order for the SDK to process touch events properly, user interaction
  // should be disabled.
  nativeAdView.callToActionView.userInteractionEnabled = NO;
}
Our GitHub repository has the complete implementations for native custom rendering ads written in both Swift and Objective-C.

Download Google Ad Manager Custom Rendering Example

GADMediaView

Image and video assets are displayed to users via GADMediaView. This is a UIView that can be defined in a xib file or constructed dynamically. It should be placed within the view hierarchy of a GADNativeAdView, as with any other asset view.

Unlike other asset views, however, apps do not need to manually populate a GADMediaView with its asset. The SDK handles this automatically once the nativeAd property is set:

  • If a video asset is available, it's buffered and starts playing inside the GADMediaView.
  • If the ad does not contain a video asset, the first image asset is downloaded and placed inside the GADMediaView instead.

    Here's a snippet from the Custom Rendering example: (Swift | Objective-C) that shows how to populate the GADMediaView with the native ad assets by associating the native ad with the native ad view:

Swift

nativeAdView.nativeAd = nativeAd

Objective-C

nativeAdView.nativeAd = nativeAd;

Ensure that in your interface builder file for your native ad view that you have the views custom class set to GADMediaView and you have connected it to the mediaView outlet.

Native video

In addition to images, text, and numbers, some native ads contain video assets. Not every ad will have one and apps are not required to display videos when they're included with an ad.

GADVideoController

The GADVideoController class is used to retrieve information about video assets. GADUnifiedNativeAd offers a videoController property that exposes the GADVideoController for each ad:

Swift

let videoController = myUnifiedNativeAd.videoController

Objective-C

GADVideoController *videoController = myUnifiedNativeAd.videoController

This property is never nil, even when the ad doesn't contain a video asset.

GADVideoController offers the following methods for querying video state:

  • hasVideoContent - True if the ad includes a video asset, false otherwise.
  • aspectRatio - The aspect ratio of the video (width/height) or 0 (zero) (if no video asset is present).

Apps can also set a GADVideoControllerDelegate for the GADVideoController to be notified of events in the lifecycle of a video asset. GADVideoControllerDelegate offers a single optional message, videoControllerDidEndVideoPlayback, which is sent when a video completes playback.

Here's an example of GADVideoControllerDelegate in action:

Swift

class ViewController: UIViewController, GADUnifiedNativeAdLoaderDelegate,
    GADVideoControllerDelegate {

  func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd:
                GADUnifiedNativeAd) {
    ...
    nativeAd.videoController.delegate = self
    ...
  }

  ...
  func videoControllerDidEndVideoPlayback(_ videoController: Any!) {
    // Here apps can take action knowing video playback is finished.
    // This is handy for things like unmuting audio, and so on.
  }
}

Objective-C

@interface ViewController () <GADUnifiedNativeAdLoaderDelegate,
        GADVideoControllerDelegate>

- (void)adLoader:(GADAdLoader *)adLoader
    didReceiveNativeAd:(GADUnifiedNativeAd) *)nativeAd {
  ...
  nativeAd.videoController.delegate = self;
  ...
}

...

- (void)videoControllerDidEndVideoPlayback:(GADVideoController *)videoController {
  // Here apps can take action knowing video playback is finished.
  // This is handy for things like unmuting audio, and so on.
}

@end

Custom ad formats

Like their system-defined counterparts, custom native ad formats are loaded using GADAdLoader objects. Including the kGADAdLoaderAdTypeNativeCustomTemplate constant in the adTypes array when initializing a GADAdLoader will configure it to request custom native formats when loading ads.

GADNativeCustomTemplateAdLoaderDelegate

The protocol for loading custom templates has two methods. The first is used by GADAdLoader to find out which template IDs it should request:

Swift

public func nativeCustomTemplateIDs(for adLoader: GADAdLoader) -> [Any]

Objective-C

- (NSArray *)nativeCustomTemplateIDsForAdLoader:(GADAdLoader *)adLoader;

Every custom native ad format has a corresponding template ID that identifies it. When this method is called, your app should return an array containing the template IDs of the formats it's prepared to display.

The second message is sent when the custom template ad has loaded, much like those for system-defined formats:

Swift

public func adLoader(_ adLoader: GADAdLoader,
    didReceive nativeCustomTemplateAd: GADNativeCustomTemplateAd)

Objective-C

- (void)adLoader:(GADAdLoader *)adLoader
    didReceiveNativeCustomTemplateAd:(GADNativeCustomTemplateAd *)nativeCustomTemplateAd;

Template IDs

The template IDs used to uniquely refer to native custom ad formats can be found in the Ad Manager UI under the Creatives > Native Ad Formats section of the Delivery tab:

Each custom native ad format's template ID appears beneath its name. Clicking on one of the names brings you to a details screen showing information about the template's fields:

From here, individual fields can be added, edited, and removed. Note the Variable ID column to the right. These IDs are used to access the individual assets, and will be discussed more in the next section.

Displaying custom native ad formats

Custom native ad formats differ from system-defined formats in that publishers have the power to define their own "templates," or lists of assets, that make up an ad. Because of this, the process for displaying custom native ads differs from the one for system-defined formats in a few ways:

  1. Because GADNativeCustomTemplateAd is meant to handle any of the custom native ad formats you create, it doesn't have named asset accessors. Instead, it offers methods like imageForKey: and stringForKey: that take the Variable ID of a template field as an argument.
  2. There is no dedicated ad view class like GADNativeContentAdView to use with GADNativeCustomTemplateAd. You are free to use whatever interface makes sense for your user experience.
  3. Because there is no dedicated ad view class, you do not need to register any of the views you use to display the ad's assets.

Here is an example of an ad view capable of displaying a simple custom native ad:

MySimpleNativeAdView.h

Swift

import UIKit
import GoogleMobileAds

/// Custom native ad view class with template ID 10063170.
class MySimpleNativeAdView: UIView {

  /// Weak references to this ad's asset views.
  @IBOutlet weak var headlineView: UILabel!
  @IBOutlet weak var mainImageView: UIImageView!
  @IBOutlet weak var captionView: UILabel!

  ...

  /// Populates the ad view with the custom native ad object.
  func populateWithCustomNativeAd(_ customNativeAd: GADNativeCustomTemplateAd) {
    ...
  }
}

Objective-C

@import UIKit;
@import GoogleMobileAds;

/// View representing a custom native ad format with template ID 10063170.
@interface MySimpleNativeAdView : UIView

// Weak references to this ad's asset views.
@property(weak, nonatomic) IBOutlet UILabel *headlineView;
@property(weak, nonatomic) IBOutlet UIImageView *mainImageView;
@property(weak, nonatomic) IBOutlet UILabel *captionView;

/// Populates the ad view with the custom native ad object.
- (void)populateWithCustomNativeAd:(GADNativeCustomTemplateAd *)customNativeAd;

@end

MySimpleNativeAdView.m (excerpt)

Swift

...
func populateWithCustomNativeAd(_ customNativeAd: GADNativeCustomTemplateAd) {
  self.customNativeAd = customNativeAd

  // Populate the custom native ad assets.
  headlineView.text = self.customNativeAd.stringForKey("Headline")
  mainImageView.image = self.customNativeAd.imageForKey("MainImage")?.image
  captionView.text = self.customNativeAd.stringForKey("Caption")
}
...

Objective-C

...
- (void)populateWithCustomNativeAd:(GADNativeCustomTemplateAd *)customNativeAd {
  self.customNativeAd = customNativeAd;

  // Populate the custom native ad assets.
  self.headlineView.text = [customNativeAd stringForKey:@"Headline"];
  self.mainImageView.image = [customNativeAd imageForKey:@"MainImage"].image;
  self.captionView.text = [customNativeAd stringForKey:@"Caption"];
}
...

Native video for custom native ad formats

When creating a new native ad format, you have the option to make the format eligible for video.

Simply check the box to make your format video eligible, and when you make a new creative for this format, you'll have an option to provide a video asset.

In your app implementation, you can use the GADNativeCustomTemplateAd.mediaView property to get the video's view. Then add this view to your view hierarchy. If the ad doesn't have video content, make alternate plans to show the ad without a video.

The example below checks if the ad has video content, and displays an image in its place if a video is not available:

Swift

...
  /// Populates the ad view with the custom native ad object.
  func populate(withCustomNativeAd customNativeAd: GADNativeCustomTemplateAd) {
    if customNativeAd.videoController.hasVideoContent(),
      let mediaView = customNativeAd.mediaView {
      updateMainView(mediaView)
    } else {
      // Assumes your native format has an image asset with the name MainImage.
      let image: UIImage? = customNativeAd.image(forKey: "MainImage")?.image
      updateMainView(UIImageView(image: image))
    }
  }

  private func updateMainView(_ mainView:UIView) {
    // Assumes you have a placeholder view for your media content.
    // Remove all the placeholder's subviews.
    for subview: UIView in mainPlaceholder.subviews {
      subview.removeFromSuperview()
    }
    mainPlaceholder.addSubview(mainView)
    // Size the media view to fill our container size.
    mainView.translatesAutoresizingMaskIntoConstraints = false
    let viewDictionary: [AnyHashable: Any] = ["mainView":mainView]
    mainPlaceholder.addConstraints(NSLayoutConstraint.constraints(
      withVisualFormat: "H:|[mainView]|", options: [], metrics: nil,
      views: viewDictionary as? [String : Any] ?? [String : Any]()))
    mainPlaceholder.addConstraints(NSLayoutConstraint.constraints(
      withVisualFormat: "V:|[mainView]|", options: [], metrics: nil,
      views: viewDictionary as? [String : Any] ?? [String : Any]()))
  }
...

Objective-C

...
- (void)populateWithCustomNativeAd:(GADNativeCustomTemplateAd *)ad {
  UIView *mainView = nil;
  if (ad.videoController.hasVideoContent) {
    mainView = ad.mediaView;
  } else {
    // Assumes your native format has an image asset with the name MainImage.
    UIImage *image = [ad imageForKey:@"MainImage"].image;
    mainView = [[UIImageView alloc] initWithImage:image];
  }
  // Assumes you have a placeholder view for your media content.
  for (UIView *subview in self.mainPlaceholder.subviews) {
    [subview removeFromSuperview];
  }
  [self.mainPlaceholder addSubview:mainView];

  // Size the main view to fill our container size.
  [mainView setTranslatesAutoresizingMaskIntoConstraints:NO];
  NSDictionary *viewDictionary = NSDictionaryOfVariableBindings(mainView);
  [self.mainPlaceholder
      addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[mainView]|"
                                                             options:0
                                                             metrics:nil
                                                               views:viewDictionary]];
  [self.mainPlaceholder
      addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[mainView]|"
                                                             options:0
                                                             metrics:nil
                                                               views:viewDictionary]];
}
...

See GADVideoController for more information on how you can customize a custom native ad's video experience.

Download the Ad Manager Custom Rendering example for a working example of native video in action.

Handling custom native ad clicks and impressions

For custom native ad formats, your app is responsible for recording impressions and for reporting click events to the SDK.

Recording impressions

To record an impression for a custom template ad, just call the recordImpression method on the corresponding GADNativeCustomTemplateAd:

Swift

myCustomTemplateAd.recordImpression()

Objective-C

[myCustomTemplateAd recordImpression];

The SDK prevents duplicate impressions from being recorded for a single request, should your app accidentally call the method multiple times for the same ad.

Reporting clicks

To report to the SDK that a click has occurred on an asset view, call the performClickOnAssetWithKey: method on the corresponding GADNativeCustomTemplateAd and pass in the name of the asset that was clicked. For example, if you had an asset in your custom template called "MainImage" and wanted to report a click on the view that corresponded to that asset, your code would look like this:

Swift

myCustomTemplateAd.performClickOnAsset(withKey: "MainImage")

Objective-C

[myCustomTemplateAd performClickOnAssetWithKey:@"MainImage"];

Note that you don't need to call this method for every asset view associated with your ad. If you had another asset called "Caption," for instance, that was meant to be displayed but not clicked or tapped on by the user, your app would not need to call performClickOnAssetWithKey: for that view.

Responding to custom click actions

GADNativeCustomTemplateAd has a property customClickHandler which is of type GADNativeAdCustomClickHandler

Swift

typealias GADNativeAdCustomClickHandler = (assetID: String) -> Void

Objective-C

typedef void (^GADNativeAdCustomClickHandler)(NSString *assetID);

This is a block (Objective-C) / closure (Swift) that accepts an assetID as an input parameter, which identifies the asset that has been clicked on.

When a click is performed on a custom template ad, there are three possible responses from the SDK, attempted in this order:

  1. Invoke the customClickHandler block in Objective-C or closure in Swift, if one was set.
  2. Loop through the ad's Deeplink URLs and open the first one for which a matching app can be found.
  3. Open a browser and navigate to the ad's traditional Destination URL.

The customClickHandler property accepts a block in Objective-C and a closure in Swift. If you set a block or closure, the SDK will run it and take no further action. If you set a nil value, however, the SDK will fall back to the deeplink and/or destination URLs registered with the ad.

Custom click handlers allow your app to decide for itself the best action to take in response to a click, whether it's updating the UI, presenting another view controller, or merely logging the click. Here's an example that shows an alert:

Swift

myCustomTemplateAd.customClickHandler = { assetID in
  if assetID == "MainImage" {
    let alertView = UIAlertView(title: "Custom Click",
        message: "You just clicked on the image!",
        delegate: self,
        cancelButtonTitle: "OK")
    alertView.alertViewStyle = .default
    alertView.show()
  }
}
myCustomTemplateAd.performClickOnAsset(withKey: "MainImage")

Objective-C

[self.customTemplateAd setCustomClickHandler:^(NSString *assetID){
  if ([assetID isEqualToString:@"MainImage"]) {
    [[[UIAlertView alloc] initWithTitle:@"Custom Click"
                                message:@"You just clicked on the image!"
                               delegate:self
                      cancelButtonTitle:@"OK"
                      otherButtonTitles:nil] show];
  }
}];
[self.customTemplateAd performClickOnAssetWithKey:@"MainImage"];

Testing native ad code

Direct-sold ads

If you'd like to test out what direct-sold native ads are like, you can make use of this Ad Manager ad unit ID:

/6499/example/native

It's configured to serve sample app install and content ads, as well as a custom native ad format with the following assets:

  • Headline (text)
  • MainImage (image)
  • Caption (text)

Native backfill ads

To test the behavior of native backfill ads, use this Ad Manager ad unit:

/6499/example/native-backfill

It will serve sample app install and content ads that include the AdChoices overlay.

Remember to update your code to refer to your actual ad unit and template IDs before going live!

Send feedback about...

Mobile Ads SDK for iOS
Mobile Ads SDK for iOS
Need help? Visit our support page.