【发布时间】: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