在AppDelegate中预加载adMob插页式广告,并在其他UIViewController中显示广告

时间:2017-01-12 11:19:50

标签: swift admob appdelegate preload interstitial

我正在尝试在AppDelegate中预加载插页式广告:didFinishLaunchingWithOptions,然后在另一个UIViewController的viewWillAppear方法中显示它。 已经搜索了几个小时,答案是在Objective-C中我无法完全理解/转换为Swift或者只是不工作。请帮助我指出正确的方向。

class AppDelegate: UIResponder, UIApplicationDelegate, GADInterstitialDelegate {

    var window: UIWindow?
    var interstitial: GADInterstitial!
    var gViewController = UIViewController()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        FIRApp.configure()

        GADMobileAds.configure(withApplicationID: "MY APP ID")

        createAndLoadInterstitial()

        return true
    }


    func createAndLoadInterstitial() -> GADInterstitial {
        interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
        interstitial.delegate = self
        interstitial.load(GADRequest())
        return interstitial
    }

    func interstitialDidReceiveAd(_ ad: GADInterstitial) {

        interstitial.present(fromRootViewController: self.gViewController)

    }

    func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        interstitial = createAndLoadInterstitial()
    }

}

在其他UIViewContoller中:

var interstitial: GADInterstitial!

 override func viewWillAppear(_ animated: Bool) {

    let App = UIApplication.shared.delegate as! AppDelegate

    App.gViewController = self

    if interstitial.isReady {

        interstitial.present(fromRootViewController: self)

    } else {

        print("Ad not ready")

    }


}

给出错误:在展开可选值时意外发现nil

1 个答案:

答案 0 :(得分:0)

您有两个单独的interstitial对象,一个在课程AppDelegate中,另一个在课程UIViewController中,只有课程AppDelegate中的一个会被启动,这就是访问时的原因班级interstitial中的UIViewController仍然是nil

如果您想从AppDelegate {}获取UIViewController中的变量:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    // Now you can access it
    if appDelegate.interstitial.isReady {
        appDelegate.interstitial.present(fromRootViewController: self)
    } else {
        print("Ad not ready")
    }
}