Skip to content

Instantly share code, notes, and snippets.

@delba
Last active August 29, 2015 14:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save delba/a970927d81a85739d291 to your computer and use it in GitHub Desktop.
Save delba/a970927d81a85739d291 to your computer and use it in GitHub Desktop.
MoPub iOS sdk with Swift
import UIKit
class AdTableViewCell: UITableViewCell {
// MARK: Subviews
// Add subviews and constraints...
}
extension AdTableViewCell: MPNativeAdRendering {
static func sizeWithMaximumWidth(maximumWidth: CGFloat) -> CGSize {
return CGSize(width: maximumWidth, height: 280)
}
func layoutAdAssets(adObject: MPNativeAd!) {
adObject.loadIconIntoImageView(iconImageView)
adObject.loadTitleIntoLabel(titleLabel)
adObject.loadCallToActionTextIntoButton(callToActionButton)
adObject.loadImageIntoImageView(mainImageView)
adObject.loadTextIntoLabel(mainTextLabel)
}
}
import UIKit
import MoPub
class TableViewController: UIViewController {
// MARK: Data
var items: [Item]! {
didSet {
tableView.mp_reloadData()
}
}
// MARK: Subviews
var tableView: UITableView!
// MARK: AdPlacer
var placer: MPTableViewAdPlacer!
// MARK: UIViewController
overrider viewDidLoad() {
tableView = UITableView(frame: view.bounds)
view.addSubview(tableView)
tableView.mp_setDataSource(self)
tableView.mp_setDelegate(self)
setPlacer()
}
private func setPlacer() {
let positioning = MPServerAdPositioning()
// Set up your preferred ad positioning in the MoPub UI in the ad unit settings page.
// This is a sample ad unit ID configured to place ads at cell positions 2, 10, and every
// 10th position afterwards. You should replace this with your own ad unit ID from the
// MoPub website.
let sampleAdUnitID = "76a3fefaced247959582d2d2df6f4757"
var targeting: MPNativeAdRequestTargeting! = MPNativeAdRequestTargeting()
targeting.desiredAssets = NSSet(objects: kAdIconImageKey, kAdMainImageKey, kAdCTATextKey, kAdTextKey, kAdTitleKey) as Set<NSObject>
// Creates a table view ad placer that uses a sample cell for its layout.
// Replace the defaultAdRenderingClass with your own subclass that implements MPAdRendering.
placer = MPTableViewAdPlacer(tableView: tableView, viewController: self, defaultAdRenderingClass: AdTableViewCell.self)
placer.loadAdsForAdUnitID(sampleAdUnitID, targeting: targeting)
}
}
extension TableViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.mp_dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! TableViewCellitems[indexPath.row]
cell.item = items[indexPath.row]
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment