Swift and Banners


#1

I am trying to load an MoPub banner using swift but nothing gets displayed, no debug messages to console at all.

It seems so simple but it just won’t work, any help would be appreciated!

here is a brief code example:

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, MPAdViewDelegate {  
    var adView: MPAdView = MPAdView()
}
 override func viewDidLoad() {
        super.viewDidLoad()

 self.adView.delegate = self
        self.adView.adUnitId = MYADID
        self.adView.frame = CGRectMake((self.view.bounds.size.width - MOPUB_BANNER_SIZE.width) / 2, self.view.bounds.size.height - MOPUB_BANNER_SIZE.height, MOPUB_BANNER_SIZE.width,MOPUB_BANNER_SIZE.height)
        
  self.view.addSubview(self.adView)
  self.adView.loadAd()
}

 func viewControllerForPresentingModalView() ->UIViewController {
        println("Delegate was called! ")
        return self        
}

#2

Have you looked at the iOS sample app for Fabric - Cannonball? that is also written in Swift and may provide some clues (although I believe it uses native ads rather than banners).


#3

Thanks for reaching out. Just wanted to add some more specifics for you.

The following line in the code should be changed:

var adView: MPAdView = MPAdView()

This should read:

var adView: MPAdView = MPAdView(adUnitId: "AD_UNIT_ID", size: MOPUB_BANNER_SIZE)

Your AD_UNIT_ID should be obtained via logging in to MoPub.

For further reference you can implement two functions to verify whether the ad loaded e.g. adViewDidFailToLoadAd, adViewDidLoadAd. Here is a sample example for you:

 import UIKit
 import MoPub


class ViewController: UIViewController, MPAdViewDelegate {
    var adView: MPAdView = MPAdView(adUnitId: "AD_UNIT_ID", size: MOPUB_BANNER_SIZE)
    override func viewDidLoad() {
        super.viewDidLoad()
        self.adView.delegate = self
        self.adView.frame = CGRectMake(0, self.view.bounds.size.height - MOPUB_BANNER_SIZE.height,
        MOPUB_BANNER_SIZE.width, MOPUB_BANNER_SIZE.height)
        self.view.addSubview(self.adView)
        self.adView.loadAd()
    }

    // Function for failed "loading" of an ad.
    func adViewDidFailToLoadAd(view: MPAdView!) {
        println("Failed to load ad")
    }

    // Function for successful loading of ad.
    func adViewDidLoadAd(view: MPAdView!) {
        println("The ad loaded")
    }

    func viewControllerForPresentingModalView() -> UIViewController {
        return self
    }
}