How To Integrate Admob native Ads in iOS CollectionView or TableView Swift

How To Integrate Admob native Ads in iOS CollectionView or TableView Swift

Before integrating Admob native ads into your app, create an Admob account and download the SDK using Cocoapods.

pod 'Google-Mobile-Ads-SDK' # Mobile ads google

Testing Ads

It’s always advised you use a test Ad unit when testing your apps. Testing your app using live ads could lead to your account being terminated or suspended. Admob’s available test ads:

FormatSizeAd unit ID
Banner320×500ac59b0996d947309c33f59d6676399f
Banner (MRect)300×2502aae44d2ab91424d9850870af33e5af7
Interstitial320×4804f117153f5c24fa6a3a92b818a5eb630
Rewarded Ad320×4808f000bd5e00246de9c789eed39ff6096
Rewarded Playable (MRAID)320×48098c29e015e7346bd9c380b1467b33850
NativeN/A76a3fefaced247959582d2d2df6f4757

You also need to edit your “info.plist” to add AdMob supported networks. A full list can be downloaded here.

Getting Started

Admob doesn’t provide an out of the box solution for showing native ads on UICollectionView or UITableView. This solution provides a quick fix and largely focuses on UICollectionView but the same logic applies to UITableView. This solution addresses the problem in 3 parts: Getting the ad, presenting it in a UICollectionView and handling events (such as impressions and clicks).

The logic is: Once you query your database or data source for a list of items. You divide your result by the number of times you would like your ad to appear. 

For example, if you’d like to show your native ad every 7th row, for a list of 14 items, you’ll need 2 ad units (14 divided by 7) for the 7th and 14th row. Then insert it between the 6th and 7th row and the 13th and 14th row.

Innitialise Ads

The first step in integrating your Ad is by initialising it in your App Delegate. To initialise your Ads, import Admob and configure your ads.

import GoogleMobileAds // Mobile advertising

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:    [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        // Google services
        GADMobileAds.sharedInstance().start(completionHandler: nil)
     }
}

Load Ads

On your ViewController (i.e the controller you would like the ad to show) import the SDK and prepare the variables as seen below.

import GoogleMobileAds // Google Ads

Prepare variables

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

  // Prepare outlets vars
  @IBOutlet weak var ourCollectionView: UICollectionView! // Created using storyboard.

  // Prepare variables
  var yourItemList = [AnyObject]()

  // For mobile ads
  var adNativeUnit = "YOUR_AD_UNIT"
    
  // Admob variables
  var adiPath = 6 // Nth item for ads
  var adReq = 0 
  var adToShow = 0 // Nuber of ads to show
  var adRetCnt = 0 // Number of items returned

  /// The native ads.
  var nativeAds = [GADNativeAd]()

  /// The ad loader that loads the native ads.
  var adLoader: GADAdLoader!

  override func viewDidLoad() {
          super.viewDidLoad()
  }
}

Then add the function to load the native Ads. In this case, “adCnt” is the number of Ads you would like to load.

func loadNativeAd(adCnt: Int) {
        
        let multipleAdsOptions = GADMultipleAdsAdLoaderOptions()
            multipleAdsOptions.numberOfAds = adCnt
        self.adLoader = GADAdLoader(adUnitID: self.adNativeUnit, rootViewController: self,
                adTypes: [.native],
                options: [multipleAdsOptions])
        self.adLoader.delegate = self
        self.adLoader.load(GADRequest())
    }

The next step is to add the delegates to your ViewController, it should look similar to below.

extension ViewController: GADNativeAdLoaderDelegate, GADNativeAdDelegate  {
    
  func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) {
     print("Failed to receive ads")
  }

  func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
     // A native ad has loaded, and can be displayed.
     self.nativeAds.append(nativeAd)
  }
 
  func adLoaderDidFinishLoading(_ adLoader: GADAdLoader) {
          
     // The adLoader has finished loading ads, and a new request can be sent.
     let ItmCnt = self.adRetCnt
     var adDiv: Float = Float((ItmCnt / 6))
     adDiv = adDiv.rounded(.down)
          
     for _ in 0..<Int(adDiv) {
         let nativeAd = self.nativeAds[self.adToShow]
         self.yourItemList.insert(nativeAd, at: self.adiPath)
         self.adiPath += 6
     }
          
     self.ourCollectionView.reloadData()
     self.adReq += 6
     self.adToShow += 1
   }

// This for debugging
func nativeAdDidRecordImpression(_ nativeAd: GADNativeAd) {
   print("The native ad was shown.")
}

func nativeAdDidRecordClick(_ nativeAd: GADNativeAd) {
    print("The native ad was clicked on.")
}

func nativeAdWillPresentScreen(_ nativeAd: GADNativeAd) {
    print("The native ad will present a full screen view.")
}

func nativeAdWillDismissScreen(_ nativeAd: GADNativeAd) {
   print("The native ad will dismiss a full screen view.")
}

func nativeAdDidDismissScreen(_ nativeAd: GADNativeAd) {
   print("The native ad did dismiss a full screen view.")
}

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

Presenting Your Ad

To present your ad and ensure events (such as impressions and clicks) are registered, create a Xib file that contains the right items such as the headline, media, icon and much more and set it’s to GADNativeAdView. You can download one here.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

  let dict = eventlist[indexPath.item]
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CELL_ID", for: indexPath) as! YOUR_CELL_CLASS

  if dict is GADNativeAd {
  let nAd = dict as! GADNativeAd
  nAd.delegate = self
  nAd.rootViewController = self
  let nibView = Bundle.main.loadNibNamed("UnifiedNativeAdView", owner: nil, options: nil)?.first
  let nativeAdView = nibView as! GADNativeAdView
  nativeAdView.frame.size.width = cell.frame.size.width
  nativeAdView.frame.size.height = cell.frame.size.height
  cell.subviews.first?.removeFromSuperview()
  cell.addSubview(nativeAdView)
                    
  // Prepare ad content
  let nativeAd = nAd
  nativeAdView.nativeAd = nativeAd
                    
  // Add content to native view
  (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline
  nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent
                    
  (nativeAdView.bodyView as? UILabel)?.text = nativeAd.body
  nativeAdView.bodyView?.isHidden = nativeAd.body == nil
                    
  (nativeAdView.iconView as? UIImageView)?.image = nativeAd.icon?.image
  nativeAdView.iconView?.isHidden = nativeAd.icon == nil
                    
  (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser
  nativeAdView.advertiserView?.isHidden = nativeAd.advertiser == nil
                
  nativeAdView.callToActionView?.isUserInteractionEnabled = false
  } 

  else {
  // Do what ever you want to do with your cells.
 }

return cell
}

That’s it, run your app in Xcode.

Going Live

Once you are ready to go live, change your app unit to the one you’ve created on Admob.

Monitor Revenue

To monitor your app’s monetisation, set targets and much more download our Motics app.

Leave a Reply

Your email address will not be published.