React Native AdMob with native IOS implementation

AdMob is a mobile advertising company owned by Google, the have mobile sdk to be integrated with ios and Android for displaying Ads. With react native, AdMob can be implemented in native IOS and Android, and then use them in React Native code with javascript. The following are the basic steps needed to create an IOS native ui component using object-c and swift for displaying a banner ad from AdMob, and use it in React Native with javascript.

1. Add the following to the Podfile and run pod install --repo-update in the ios folder

pod 'Google-Mobile-Ads-SDK'

2. Update your Info.plist by adding the following. A GADApplicationIdentifier key with a string value of your AdMob app ID. A SKAdNetworkItems key with SKAdNetworkIdentifier values for Google (cstr6suwn9.skadnetwork) and select additional buyers who have provided these values to Google.

GADApplicationIdentifier
ca-app-pub-3940256099942544~1458002511
SKAdNetworkItems
  
    
      SKAdNetworkIdentifier
      cstr6suwn9.skadnetwork
    
    
      SKAdNetworkIdentifier
      4fzdc2evr5.skadnetwork
    
    
      SKAdNetworkIdentifier
      2fnua5tdw4.skadnetwork
    
    
      SKAdNetworkIdentifier
      ydx93a7ass.skadnetwork
    
    
      SKAdNetworkIdentifier
      5a6flpkh64.skadnetwork
    
    
      SKAdNetworkIdentifier
      p78axxw29g.skadnetwork
    
    
      SKAdNetworkIdentifier
      v72qych5uu.skadnetwork
    
    
      SKAdNetworkIdentifier
      c6k4g5qg8m.skadnetwork
    
    
      SKAdNetworkIdentifier
      s39g8k73mm.skadnetwork
    
    
      SKAdNetworkIdentifier
      3qy4746246.skadnetwork
    
    
      SKAdNetworkIdentifier
      3sh42y64q3.skadnetwork
    
    
      SKAdNetworkIdentifier
      f38h382jlk.skadnetwork
    
    
      SKAdNetworkIdentifier
      hs6bdukanm.skadnetwork
    
    
      SKAdNetworkIdentifier
      prcb7njmu6.skadnetwork
    
    
      SKAdNetworkIdentifier
      v4nxqhlyqp.skadnetwork
    
    
      SKAdNetworkIdentifier
      wzmmz9fp6w.skadnetwork
    
    
      SKAdNetworkIdentifier
      yclnxrl5pm.skadnetwork
    
    
      SKAdNetworkIdentifier
      t38b2kh725.skadnetwork
    
    
      SKAdNetworkIdentifier
      7ug5zh24hu.skadnetwork
    
    
      SKAdNetworkIdentifier
      9rd848q2bz.skadnetwork
    
    
      SKAdNetworkIdentifier
      n6fk4nfna4.skadnetwork
    
    
      SKAdNetworkIdentifier
      kbd757ywx3.skadnetwork
    
    
      SKAdNetworkIdentifier
      9t245vhmpl.skadnetwork
    
    
      SKAdNetworkIdentifier
      4468km3ulz.skadnetwork
    
    
      SKAdNetworkIdentifier
      2u9pt9hc89.skadnetwork
    
    
      SKAdNetworkIdentifier
      8s468mfl3y.skadnetwork
    
    
      SKAdNetworkIdentifier
      av6w8kgt66.skadnetwork
    
    
      SKAdNetworkIdentifier
      klf5c3l5u5.skadnetwork
    
    
      SKAdNetworkIdentifier
      ppxm28t8ap.skadnetwork
    
    
      SKAdNetworkIdentifier
      424m5254lk.skadnetwork
    
    
      SKAdNetworkIdentifier
      uw77j35x4d.skadnetwork
    
    
      SKAdNetworkIdentifier
      578prtvx9j.skadnetwork
    
    
      SKAdNetworkIdentifier
      4dzt52r2t5.skadnetwork
    
    
      SKAdNetworkIdentifier
      e5fvkxwrpn.skadnetwork
    
    
      SKAdNetworkIdentifier
      8c4e2ghe7u.skadnetwork
    
    
      SKAdNetworkIdentifier
      zq492l623r.skadnetwork
    
    
      SKAdNetworkIdentifier
      3qcr597p9d.skadnetwork
    
  

3. 1. In XCode, create a new file: File -> New -> File… -> Cocoa Touch Class, name it AdMobView and add the following. This file is the main ui component for displaying the banner ad. ca-app-pub-3940256099942544/6300978111 is a test ad id, you can replace it with your own.

import UIKit
import GoogleMobileAds

class AdMobView: UIView {

  @objc var adId: String = "ca-app-pub-3940256099942544/6300978111" {
    didSet {
      self.setupView()
    }
  }
  
  // green, app primary color
  @objc var bgColor: String? {
    didSet {
      self.setupView()
    }
  }

  var bannerView: GADBannerView!
  
  override init(frame: CGRect) {
    super.init(frame: frame)
    setupView()
  }

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupView()
  }
  
  private func setupView() {
    // set background color received from react native
    if (self.bgColor != nil) {
      self.backgroundColor = hexStringToUIColor(hex: self.bgColor!)
    }
  }
  
  private var isLoaded: Bool = false
  override func layoutSubviews() {
      super.layoutSubviews()
      if !isLoaded {
        isLoaded = true
        loadAd()
      }
    bannerView.center = CGPoint(x: bounds.midX, y: bounds.midY)
  }

}

extension AdMobView {
  
  private func loadAd() {
    // In this case, we instantiate the banner with desired ad size.
    bannerView = GADBannerView(adSize: GADAdSizeBanner)
    self.addSubview(bannerView)
    self.addConstraints(
      [NSLayoutConstraint(item: bannerView!,
                          attribute: .bottom,
                          relatedBy: .equal,
                          toItem: safeAreaLayoutGuide,
                          attribute: .top,
                          multiplier: 1,
                          constant: 0),
       NSLayoutConstraint(item: bannerView!,
                          attribute: .centerX,
                          relatedBy: .equal,
                          toItem: self,
                          attribute: .centerX,
                          multiplier: 1,
                          constant: 0)
      ])

    print("AdMobView loadAd: \(self.adId)")

    bannerView.adUnitID = self.adId
    bannerView.rootViewController = self.reactViewController()
    bannerView.load(GADRequest())
    
  }
  
  private func hexStringToUIColor (hex:String) -> UIColor {
      var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

      if (cString.hasPrefix("#")) {
          cString.remove(at: cString.startIndex)
      }

      if ((cString.count) != 6) {
          return UIColor.gray
      }

      var rgbValue:UInt64 = 0
      Scanner(string: cString).scanHexInt64(&rgbValue)

      return UIColor(
          red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
          green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
          blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
          alpha: CGFloat(1.0)
      )
  }
}

4. In XCode, create another file with the same name AdMobView but choose Object c file: File -> New -> File… -> Objective-C File, and add the following. This file defines the properties for the AdMob view and expose them to React Native.

#import 

// AdMobManager maps to AdMobView in react native requireNativeComponent('AdMobView');
// adId maps to the message prop on react native's view property
// bgColor maps to the bgColor prop on react native's view property
@interface RCT_EXTERN_MODULE(AdMobViewManager, RCTViewManager)
RCT_EXPORT_VIEW_PROPERTY(adId, NSString)
RCT_EXPORT_VIEW_PROPERTY(bgColor, NSString)
@end

5. On step 4, when creating the Object-C File, XCode will ask if you want to create a bridge file, select yes to create it. It will create a file YourProjectName-Bridging-Header.h, open this file and add the following.

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

#import 
#import 
#import 
#import 
#import 
#import 

6. Create another swift file and name it AdMobViewManager, this registers AdMobView with React Native.

@objc (AdMobViewManager)
class AdMobViewManager: RCTViewManager {

  override static func requiresMainQueueSetup() -> Bool {
    return true
  }

  override func view() -> UIView! {
    return AdMobView()
  }

}

7. Back to the React Native using any IDE such as VSCode for javascript development, create a file NativeAdMobView.tsx with the following.

import { requireNativeComponent } from 'react-native';

const NativeAdMobView = requireNativeComponent('AdMobView');
export default NativeAdMobView;

8. Create another file to render the AdMobView view AdMobView.tsx

import React from 'react';
import { StyleSheet, View } from 'react-native';
import NativeAdMobView from './NativeAdMobView';

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  btn: {
    margin: 10
  },
  adview: {
    height: 50,
    width: '100%',
  },
});

const AdMobView: React.FC = (props)=>{
  return (
    
      
    
  );
}

export default AdMobView;

9. Render AdMobView anywhere in your react native codebase like this


  

8. Lastly, reinstall the app and the ad should be displayed in IOS

react-native run-ios

Reference:
https://developers.google.com/admob/ios/quick-start#update_your_infoplist

Search within Codexpedia

Custom Search

Search the entire web

Custom Search