SwiftUI-Google AdMob插页式广告未显示在onAppear中

时间:2020-05-27 03:33:15

标签: ios swift admob swiftui interstitial

我试图在显示时显示来自Google AdMob的插页式广告,但它没有显示,并且在控制台中显示“未准备好”。我已经签出了许多其他教程,并在其上堆积了溢出页面,但没有找到答案。谁能帮我?这是我的代码:

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")
                }



    })
}
}

2 个答案:

答案 0 :(得分:0)

Google Admob强烈建议使用 interstitialDidReceiveAd 回调用于显示广告的评论中所述。相反,您可以通知视图已加载广告,然后视图应做出是否显示插页式广告的正确时间的决定。因此,只需使用 load show 函数创建一个帮助器类,如下所示:-

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

<div class="container">
 <div class="row">
   <div class="col-xs-6 col-md-3">
     <div class="alert alert-info">a</div>
   </div>
   <div class="col-xs-6 col-md-3">
     <div class="alert alert-danger">b</div>
   </div>
   <div class="col-xs-6 col-md-3">
     <div class="alert alert-info">c</div>
   </div>
   <div class="col-xs-6 col-md-3">
     <div class="alert alert-info">d</div>
   </div>
 </div>
</div>

现在仅在视图中使用此类,并且每次调用load方法时,它都会创建一个新请求(根据文档要求)。现在,您应该从视图中观察 isLoaded 布尔值,并且仅在其意图加载时才可以在屏幕上触发广​​告(使用showAd),而不是在加载时立即触发,因为我们需要考虑到该用户可能在中间的东西...

答案 1 :(得分:-1)

GADInterstitial.load是异步操作,不要等到广告加载完毕,因此,如果要在加载后立即显示添加,则必须使用委托。

这是一个可能的解决方案

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)
        })
    }
}