I am trying to show an interstitial ad from google AdMob on appearing, but It Does not show up and it says "not ready" in the console. I have checked out many other tutorials and stack overflow pages on it but haven't found the answer. Can anyone help me? Here is my code:
struct ContentView: View {
@State var interstitial: GADInterstitial!
var body: some View{
Text("Some Text").onAppear(perform: {
self.interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
let req = GADRequest()
self.interstitial.load(req)
if self.interstitial.isReady{
let root = UIApplication.shared.windows.first?.rootViewController
self.interstitial.present(fromRootViewController: root!)
}else {
print("not ready")
}
})
}
}
The GADInterstitial.load
is asynchronous operation and don't wait till ad is loaded, so you have to use delegate if you want to show add immediately after load.
Here is a possible solution
class MyDInterstitialDelegate: NSObject, GADInterstitialDelegate {
func interstitialDidReceiveAd(_ ad: GADInterstitial) {
if ad.isReady{
let root = UIApplication.shared.windows.first?.rootViewController
ad.present(fromRootViewController: root!)
} else {
print("not ready")
}
}
}
struct ContentView: View {
@State var interstitial: GADInterstitial!
private var adDelegate = MyDInterstitialDelegate()
var body: some View{
Text("Some Text").onAppear(perform: {
self.interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
self.interstitial.delegate = self.adDelegate
let req = GADRequest()
self.interstitial.load(req)
})
}
}