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

问题描述 投票:1回答:1

我正在尝试在显示时显示来自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")
                }



    })
}
}
ios swift admob swiftui interstitial
1个回答
1
投票

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

这里是可能的解决方法

class GADInterstitialDelegate: 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 = GADInterstitialDelegate()
    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)
        })
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.