Random Ads between cells

I am trying to put Ads totally randomly between cells inside a `UITableView`. The following link explains exactly what I want: https://i.stack.imgur.com/k6pnE.png


Table View Controller:

class Page1: UITableViewController, UISearchBarDelegate {

    @IBOutlet weak var searchBar: UISearchBar!
    var employeesSearching = [Employee]()
    var isSearching : Bool = false

    let collation = UILocalizedIndexedCollation.current()
    var sections: [[Any]] = []
    var objects: [Any] = [] {
        didSet {
            let selector: Selector = #selector(getter: UIApplicationShortcutItem.localizedTitle)
            sections = Array(repeating: [], count: collation.sectionTitles.count)
            let sortedObjects = collation.sortedArray(from: objects, collationStringSelector: selector)
            for object in sortedObjects {
                let sectionNumber = collation.section(for: object, collationStringSelector: selector)
                sections[sectionNumber].append(object as AnyObject)
            }
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
  
        self.searchBar.delegate = self
        self.tableView.contentOffset = CGPoint(x: 0, y: searchBar.frame.height) /
  
        Shared.instance.employees.sort {
            (first, second) in
            first.name.compare(second.name, options: .diacriticInsensitive) == .orderedAscending
        }
    }

    func getMatches(letter: String, withArray array: [Employee]) -> [Employee] {
        return array.filter({ ($0.name.compare(letter, options: .diacriticInsensitive, range: $0.name.startIndex..<$0.name.index($0.name.startIndex, offsetBy: 1), locale: nil) == .orderedSame)})
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        if isSearching { return 1 }
        return collation.sectionTitles.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let letter = collation.sectionTitles[section]
        if isSearching {
            return employeesSearching.count
        } else {
            let matches = getMatches(letter: letter, withArray: Shared.instance.employees)
            if !matches.isEmpty { return matches.count }
        }
        return 0
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if isSearching { return nil }
        let letter = collation.sectionTitles[section]
        let matches = getMatches(letter: letter, withArray: Shared.instance.employees)
        if matches.count == 0 { return nil }
        return collation.sectionTitles[section] }

    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        if isSearching { return nil }
        return collation.sectionIndexTitles }

    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return collation.section(forSectionIndexTitle: index) }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell1
        if isSearching {
            cell.nameLabel.text = employeesSearching[indexPath.row].name
            cell.positionLabel.text = employeesSearching[indexPath.row].position
        } else {
            let letter = collation.sectionTitles[indexPath.section]
            let matches = getMatches(letter: letter, withArray: Shared.instance.employees)
      
            cell.nameLabel.text = matches[indexPath.row].name
            cell.positionLabel.text = matches[indexPath.row].position
        }
        return cell
    }
    ...
    ...
    ...
}


I have just this below to be added above:

@IBOutlet weak var GoogleBannerView = GADBannerView()
GoogleBannerView?.adUnitID = "ca-app-pub-6043248661561548/4628935113"
GoogleBannerView?.rootViewController = self
GoogleBannerView?.load(GADRequest())


I guess it have to be put in cellForRowAt but anyone could explain deatiled how to add a new Prototype Cell (to be random) inside cellForRowAt? I mean how do I smuggle a UITableViewCell as! AdCell randomly into the UITableView?


Thanks!

Accepted Answer

I would create a custom UITableViewCell subclass which contains the GoogleBannerView.


You can add randomness using a built in Swift function called arc4random() to get a random number. arc4random_uniform() accepts a UInt32 parameter as the max value.


For example, arc4random_uniform(UInt32(10)) would return a random number between 0-9


let maxNumAds = UInt32(something); //some pre-determined way of determining the maximum number of ads that should appear
let numberOfAds = Int(arc4random_uniform(maxNumAds)));
var dataSource : [AnyObject] = [];

//first populate data source with Employee objects

for i in 0...numberOfAds {
  let index = Int(arc4random_uniform(UInt32(dataSource.count))); //find random index to insert at
  let ad = Ad(); //generate whatever your data source object for Ads is
  dataSource.insert(ad, at: index);
}


And now in your cellfForRow method check to see if the data source object is an Employee or an Ad object


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let object = self.dataSource[indexPath.row];

   if (object is Ad) {
     //dequeue and return an Ad table view cell
     let cell = self.tableView.dequeueReusableCell(withIdentifier: "adCell", for: indexPath) as! AdCell;
     cell.setupCell(withAd: object as! Ad);
     return cell;
   } else {
     //dequeue and return an Employee table view cell
     let cell = self.tableView.dequeueReusableCell(withIdentifier: "employeeCell", for: indexPath) as! EmployeeCell;
     cell.setupCell(withEmployee: object as! Employee);
     return cell;
   }
}
Random Ads between cells
 
 
Q