【问题标题】:How do I call an interstitial ad to load on another UIViewController?如何调用插页式广告加载到另一个 UIViewController?
【发布时间】:2020-03-29 17:05:41
【问题描述】:

我有一个 UIViewController,上面显示了一个 UIView;按下 UIView 上的按钮加载我的插页式广告。随后显示 UIView 时,我希望以 rootVC 作为 UIViewController 显示插页式广告。

但是,此代码似乎无法按预期工作:

1) 我的视图控制器:

class MyViewController: UIViewController {

let button: UIButton = {
    let btn = UIButton()
    btn.translatesAutoresizingMaskIntoConstraints = false
    btn.setTitle("BUTTON", for: .normal)
    btn.addTarget(self, action: #selector(showUIView), for: .touchUpInside)
    return btn
}() 
@objc func showUIView(_ sender: UIButton) {
let popUp = MyUIView()
self.view.addSubview(popUp)
}

2) 我的 UIView:

class MyUIView: UIView {

var interstitial: GADInterstitial!

let button: UIButton = {
let btn = UIButton()
btn.translatesAutoresizingMaskIntoConstraints = false
btn.setTitle("UIVIEW BUTTON", for: .normal)
btn.addTarget(self, action: #selector(prepareInterstitial), for: .touchUpInside)
return btn
}()

@objc func prepareInterstitial(_ sender: UIButton) {
    interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
    let request = GADRequest()
    interstitial.load(request)

dismissPopUp()

if interstitial.isReady {
  interstitial.present(fromRootViewController: MyViewController())
       }
  }

我在控制台中得到了这个:

Warning: Attempt to present <GADFullScreenAdViewController: 0x7f8611e22fc0> on <Project.MyViewController: 0x7f8612884800> whose view is not in the window hierarchy!`

我不明白,因为 MyViewController 仍然是视图层次结构的一部分。

如果有人能告诉我如何修复此错误,我将不胜感激,我对编码比较陌生,不确定自己做错了什么。谢谢!

【问题讨论】:

    标签: swift uiview uiviewcontroller admob


    【解决方案1】:

    这不起作用的原因是因为您在这里创建了一个全新的 VC:

    interstitial.present(fromRootViewController: MyViewController())
    

    这个MyViewController()不是屏幕上显示的VC!您刚刚通过调用它的初始化程序来创建。

    您需要以某种方式获取屏幕上显示的 VC。一种简单的方法是将rootVC 属性添加到您的MyUIView

    weak var rootVC: UIViewController?
    

    然后改为呈现这个:

    if let rootVC = self.rootVC { // nil check!
        interstitial.present(fromRootViewController: rootVC)
    }
    

    showUIView 中,将self 设置为rootVC

    @objc func showUIView(_ sender: UIButton) {
        let popUp = MyUIView()
        popUp.rootVC = self
        self.view.addSubview(popUp)
    }
    

    【讨论】:

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