viewDidLoad(AdMob)上的Swift插页式广告

时间:2016-02-05 04:34:56

标签: ios swift admob

我正在关注此tutorial

到目前为止,当我点击按钮时,我可以使用它。但是我似乎无法在viewDidLoad上显示插页式广告。

这就是我所拥有的:

override func viewDidLoad() {
  super.viewDidLoad()
  self.interstitialAd = GADInterstitial(adUnitID: "ADUnitID")

  let request = GADRequest()

  // Requests test ads on test devices.
  request.testDevices = ["2077ef9a63d2b398840261c8221a0c9b"]

  self.interstitialAd.loadRequest(request)
  self.interstitialAd = reloadInterstitialAd()
}

控制台一直向我显示:

  

2016-02-04 22:27:51.855 GoogleAdMobTutorial [3394:56415]要在此设备上投放测试广告,请致电:request.testDevices = @ [kGADSimulatorID];

当我点击按钮时:

@IBAction func showAd(sender: AnyObject) {
    if self.interstitialAd.isReady {
        self.interstitialAd.presentFromRootViewController(self)
    }
}

广告出现了。当我关闭广告时,我会在控制台中看到它:

  

2016-02-04 22:29:16.661 GoogleAdMobTutorial [3394:56743]请求错误:由于使用了插页式对象,因此无法发送请求。

这是我关闭广告时调用的函数:

func interstitialDidDismissScreen(ad: GADInterstitial!) {
    self.interstitialAd = reloadInterstitialAd()
}

问题

为了清楚起见:如何在视图控件加载时显示插页式广告?

1 个答案:

答案 0 :(得分:7)

在任何viewController中,添加此函数。

   override func viewDidLoad() {
    super.viewDidLoad()

    let App = UIApplication.sharedApplication().delegate as! AppDelegate
    App.gViewController = self;
    App.showAdmobInterstitial()
}

//在AppDelegate中,将gViewController声明为成员变量

  var gViewController: UIViewController?
  var mInterstitial: GADInterstitial!

在AppDelegate类中添加这些功能

    func showAdmobInterstitial()
    {
            let kGoogleFullScreenAppUnitID = "ca-app-pub-***";
            self.mInterstitial = GADInterstitial.init(adUnitID:kGoogleFullScreenAppUnitID )

            mInterstitial.delegate = self
            let Request  = GADRequest()
            Request.testDevices = ["2077ef9a63d2b398840261c8221a0c9b"]
            mInterstitial.loadRequest(Request)
    }

    func interstitialDidReceiveAd(ad: GADInterstitial!)
    {
        ad.presentFromRootViewController(self.gViewController)
    }

确保在AppDelegate中添加了GADInterstitialDelegate。

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GADInterstitialDelegate {