在视图之间导航时显示插页式广告

Showing an interstitial while navigating between views

我有一个名为 RootVC 的最顶层 parent 或根 UIViewController。有 3 个 child 或叶子 UIViewController 称为 ChildAChildBChildC 继承自 RootVC.
ChildAChildBChildC 有一个与之关联的 UIView,用户可以导航通过点击每个视图上的内容在 A、B 和 C 之间来回切换。

RootVC 中,我有显示 Interstitial 广告的代码。我计算用户在每个 ViewDidAppear() 中来回导航的次数,并在一定计数后调用插页式广告。

因此,只要调用插页式广告的条件为真,就会通过以下调用调用插页式广告:

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

这里我传递 self 作为参数。到目前为止一切顺利。

如果用户在间隙条件变为真时停留在视图上,则此安排工作正常。但是如果视图发生变化,我会收到警告:

尝试在 上展示 ,其视图不在 window 层次结构中!

插页明显不显示。 所以我想问一下如何以正确的方式做到这一点?在这种情况下是否有既定的设计模式来显示插页式广告?

一个解决方案是实施 UINavigationControllerDelegate,特别是 navigationController:willShowViewController:animated:

当您检测到要显示插页式广告时,从 willShowViewController 调用 rootVC 的 func presentViewController() 方法并传递插页式视图控制器。