iOS开发用swift添加iAd广告

第一步,在storyboard中拖入一个iAd BannerView控件,做好布局就ok了。

技术分享

第二步,将控件引用到viewController中

技术分享

第四步,代码部分。

import UIKit
import iAd
class ViewController: UIViewController,ADBannerViewDelegate {

    @IBOutlet weak var MyAd: ADBannerView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.canDisplayBannerAds = true
        self.MyAd.delegate = self
        self.MyAd.hidden = true    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func bannerViewWillLoadAd(banner: ADBannerView!) {
        NSLog("bannerViewWillLoadAd")
    }

    func bannerViewDidLoadAd(banner: ADBannerView!) {
        NSLog("bannerViewDidLoadAd")
        self.MyAd.hidden = false //now show banner as ad is loaded
    }

    func bannerViewActionDidFinish(banner: ADBannerView!) {
        NSLog("bannerViewDidLoadAd")
        //optional resume paused game code 
    }

    func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
        NSLog("bannerViewActionShouldBegin")   
        //optional pause game code
        return true
    }

    func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
        NSLog("bannerView")
    }
    //... your class implementation code
}

注意

需要import iAd

以及接口ADBannerViewDelegate

运行之后不会马上显示,与你当前的网络状况有关,有可能会等待一段时间,祝成功!

这是成功后应该出现的情况

技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。