Wai Loon
Wai Loon

Reputation: 11

Pre-load adMob interstitial ad in AppDelegate and display the ad in other UIViewController

I am trying to pre-load interstitial ad in AppDelegate: didFinishLaunchingWithOptions and then display it in viewWillAppear method of another UIViewController. Have searched for few hours now, the answer is either in objective-C which I can't fully understand/convert to Swift or just not working. Kindly help to point me in the right direction.

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

}

In other 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")

    }


}

Gives the error: unexpectedly found nil while unwrapping an Optional value

Upvotes: 1

Views: 1436

Answers (1)

kl.woon
kl.woon

Reputation: 2055

You have two separate interstitial object, one in class AppDelegate and another in class UIViewController, and only the one in class AppDelegate gets initiated, that's why when accessing the interstitial in class UIViewController it's still nil.

If you want to access the variable in AppDelegate from 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")
    }
}

Upvotes: 0

Related Questions