Search code examples
iosswiftwebviewuiwebviewadmob

Admob is not displaying ads when using Webview in IOS


I'm developing a basic hybrid app with IOS Xcode. In app I have a UIWebview and a bottom toolbar with buttons. When user click toolbar buttons, I want to display interstitial ads and changing webview url. But ads is not displaying with message of 'Ads wasn't ready'.

If i remove webview, ads is coming correctly.

So why ads is not coming with webview? I have same android app on Google Play and it is working fine.

import UIKit
import GoogleMobileAds
class ViewController: UIViewController {

var interstitial:   GADInterstitial!  

@IBOutlet weak var webView: UIWebView!

var phoneLang = "en"

@IBAction func historyBtn(_ sender: Any) {
    displayAds()
   //todo: set webview url to go history page
  }

@IBAction func favoritesBtn(_ sender: Any) {
    displayAds()
    //todo: set webview url to go favorites page
}
override func viewDidLoad() {
    super.viewDidLoad()

    phoneLang = NSLocale.preferredLanguages[0]

    let index = phoneLang.index(phoneLang.startIndex, offsetBy: 2)
    phoneLang = phoneLang.substring(to: index)        
    UserDefaults.standard.register(defaults: ["UserAgent": "MobileApp"])

    let xurl = URL(string: "https://www.sozcukcevir.com")
    let request = URLRequest(url: xurl!)        
    webView.loadRequest(request)        
    createAds()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


fileprivate func createAds() {
    createAndLoadInterstitial()        
}

fileprivate func displayAds() {        
    if interstitial.isReady {
        interstitial.present(fromRootViewController: self)
    } else {
        print("Ad wasn't ready")
    }       
}

fileprivate func createAndLoadInterstitial() {
    interstitial = GADInterstitial(adUnitID: "ca-app-pub-5181306594932785/7917067758")
    let request = GADRequest()        
    request.testDevices = [ kGADSimulatorID, "2077ef9a63d2b398840261c8221a0c9a" ]
    interstitial.load(request)
  } 
}

Solution

  • It is about browser user agent. If I change user agent, ads are not coming. Admob needs common user agent for displaying ads.

    When I comment this code or set user agent as a known browser's value, admob ads is running well.

    UserDefaults.standard.register(defaults: ["UserAgent": "MobileApp"])
    

    to:

    // UserDefaults.standard.register(defaults: ["UserAgent": "MobileApp"])