Wednesday, 29 July 2015

iAd Integration in iOS using Swift


In most of the Apps we display the ads. Most of us have displayed the ads using different ad networks like adMob,iAd etc. Today, I will provide the details to integrate iAds in your app using swift.

The first requirement to display the iAd is to import the iAd framework. In swift you can import it by following way.

        import iAd

Once you have import the framework, you can display the iAd by writing single line in view did load.

        override func viewDidLoad() 
        {
                   super.viewDidLoad()
                   // Do any additional setup after loading the view, typically from a nib.
                  self.canDisplayBannerAds = true
        }


As soon as you set the property true, your app will be able to display the ads if iAd inventory will be available.

Note: Make sure that you write this line in viewDidLoad only.

To determine the success or failure of iAd you have to implement ADBannerViewDelegate protocol that provides the callback when ad will load successfully or will fail.

       func bannerViewDidLoadAd(banner: ADBannerView!) {
            println("success")
       }
      func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError
           error: NSError!) {
            println("failed to load ad")
            banner.removeFromSuperview() //Remove the banner if you have added it as  subview (No ad)

       }

This was a simple way to display the ads but it will display the ad in the bottom of your UI and reduce the view height when it will be loaded.


Now what you will do if you have to show it on the top of the screen ? Don't worry I will also make it easy for you.

For displaying the iAd on top of the view or any custom position, you have to create a ADBannerView and add it in your view.

        bannerV = ADBannerView(adType: ADAdType.Banner);
        bannerV.frame = CGRect(x: 0, y: 0, width: 320, height: 50);
        bannerV.delegate = self;
        self.view.addSubview(bannerV)

Here is
sample project with all the code of the above tutorial.

If you face any issue or have any suggestions, you can leave your comment.

14 comments: