Search code examples
swiftios9interstitial

Showing an interstitial while navigating between views


I have a topmost parent or root UIViewController called RootVC. There are 3 child or leaf UIViewControllers called ChildA, ChildB and ChildC which inherit from RootVC.
ChildA, ChildB and ChildC have a UIView associated with it, and user can navigate back and forth between A, B and C by tapping on contents on each view.

In the RootVC, I have the code to display an Interstitial ad. I count the number of times the user has navigated back and forth in each ViewDidAppear(), and after a certain count I invoke the interstitial ad.

So whenever the the conditions to invoke an interstitial are true, the interstitial is invoked from with the call:

presentFromRootViewController(controller: UIViewController) //Google Ads 
presentWithViewController(controller: UIViewController) //Flurry Ads

Here I am passing self as the argument. So far so good.

This arrangement works fine if the user stays on the view when the interstitial condition becomes true. But if the view changes, I get a warning:

Attempt to present < XADInterstitial > on < MyApp.ChildA > whose view is not in the window hierarchy!

The interstitial obviously does not show. So I wanted to ask how do I do this the right way? Is there an established Design Pattern to show interstitials in this kind of situation?


Solution

  • One solution would be to implement UINavigationControllerDelegate, specifically navigationController:willShowViewController:animated:.

    When you detect you want to show an interstitial, from willShowViewController, call rootVC's func presentViewController() method and pass the interstitial view controller.