【问题标题】:Pre-load adMob interstitial ad in AppDelegate and display the ad in other UIViewController在 AppDelegate 中预加载 adMob 插页式广告并在其他 UIViewController 中显示广告
【发布时间】:2017-01-12 11:19:49
【问题描述】:

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

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

【问题讨论】:

  • 为什么没有在 UIViewController 中加载它?
  • 因为上面说的 UIViewController 只是一个菜单,所以用户可能会很快点击某个按钮(在广告准备好之前)。

标签: swift admob appdelegate preload interstitial


【解决方案1】:

您有两个单独的interstitial 对象,一个在AppDelegate 类中,另一个在UIViewController 类中,并且只有AppDelegate 类中的一个被启动,这就是在访问@987654326 类中的interstitial 时的原因@还是nil

如果你想从UIViewController访问AppDelegate中的变量:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多