在 SwiftUI 中按函数调用时不会显示视图

View won't show when calling by function in SwiftUI

我有这个问题。我正在尝试使用 AdMob 在我的应用中展示广告。一切正常(我做了一些调试)但是包含视频的视图没有显示...我不明白为什么它没有显示在我的内容顶部。

这是调用和打开带有广告的视图的 class:

    import SwiftUI
import GoogleMobileAds
import UIKit
    
class Rewarded: NSObject, GADRewardedAdDelegate, ObservableObject{
    @Published var adLoaded: Bool = false
    var rewardedAd:GADRewardedAd = GADRewardedAd(adUnitID: "ca-app-pub-3940256099942544/1712485313")
    
    var rewardFunction: (() -> Void)? = nil
    
    override init() {
        super.init()
        LoadRewarded()
    }
    
    func LoadRewarded(){
        let req = GADRequest()
        self.rewardedAd.load(req) { error in
            if error != nil {
                self.adLoaded = false
                print("Ad not loaded")
            } else {
                self.adLoaded = true
                print("Ad loaded")
            }
        }
    }
    
    func showAd(rewardFunction: @escaping () -> Void){
        if self.rewardedAd.isReady {
            print("Ad is ready to show")
            self.rewardFunction = rewardFunction
            if let root = UIApplication.shared.windows.first?.rootViewController {
                self.rewardedAd.present(fromRootViewController: root, delegate: self)
                print("Presenting")
            } else {
                print("Failed to open ad")
            }
        } else {
           print("Ad not ready to show")
       }
    }
    
    func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarn reward: GADAdReward) {
        if let rf = rewardFunction {
            rf()
        }
    }
    
    func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
        self.rewardedAd = GADRewardedAd(adUnitID: "ca-app-pub-3940256099942544/1712485313")
        LoadRewarded()
    }
}

这里是调用 class 函数的代码的 SwiftUI 部分:

Button {
                            self.rewardAd.showAd(rewardFunction: {
                                // GIVE REWARD HERE
                            })
                        } label: {
                            Text("Watch Ad")
                                    .foregroundColor(Color.white)
                                .font(.custom(customFont, size: 17))
                                    .fontWeight(.bold)
                        }

控制台也没有打印任何错误...

有人知道为什么没有显示吗?

谢谢大家

这对我有用。我花了很多时间让它工作,并尝试按照我能找到的所有示例进行操作,最终找到了这个。

    func showAd(rewardFunction: @escaping () -> Void){
        if let ad = rewardedAd {
            self.rewardFunction = rewardFunction
            if let root = UIApplication.shared.windows.first?.rootViewController {
                ad.present(fromRootViewController: root, userDidEarnRewardHandler: {
                        let reward = ad.adReward
                        // reward the user
                       })
            }
            else {
                print("Error presenting ad")
            }
            
        }
        else{
           print("Ad Not Ready")
       }
    }