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

SwiftUI - Google AdMob interstitial not showing in onAppear

我试图在出现时显示来自 google AdMob 的插页式广告,但它没有显示,并且在控制台中显示 "not ready"。我已经查看了许多其他教程和堆栈溢出页面,但没有找到答案。谁能帮我?这是我的代码:

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



    })
}
}

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

如评论中所述,Google Admob 强烈反对使用 interstitialDidReceiveAd 回调来显示广告。相反,您可以通知您的视图广告已加载,然后您的视图应决定是否是显示插页式广告的正确时间。因此,只需创建一个带有 loadshow 函数的助手 class,如下所示:-

import Foundation
import GoogleMobileAds
import UIKit
    
final class InterstitialAd : NSObject, GADInterstitialDelegate, ObservableObject {
    var interstitial: GADInterstitial? = nil
    @Published var isLoaded: Bool = false
    
    func LoadInterstitial() {
        interstitial = GADInterstitial(adUnitID: Constants.interstitialAdCode)
        let req = GADRequest()
        interstitial!.load(req)
        interstitial!.delegate = self
    }
    
    func showAd() {
        if let fullScreenAd = self.interstitial, fullScreenAd.isReady {
           let root = UIApplication.shared.windows.first?.rootViewController
           fullScreenAd.present(fromRootViewController: root!)
           isLoaded = false
        }
    }
    
    func interstitialDidReceiveAd(_ ad: GADInterstitial) {
        isLoaded = true
    }
}

现在只需在您的视图中使用此 class,每次您调用加载方法时,它都会创建一个新请求(根据文档要求)。您现在应该从您的视图中观察 isLoaded 布尔值,并且可以在屏幕上触发广​​告(使用 showAd)只有当它打算而不是加载时才触发,因为我们需要考虑该用户可能正在做某事...