Search code examples
swiftxcodeuitableviewads

Random Ads between cells


I am trying to put Ads totally randomly between cells inside a UITableView. I am gonna show my main file to you understand what I am doing and how I want: Randomly Ads

Table View Controller:


class Page1: UITableViewController, UISearchBarDelegate {
    
    @IBOutlet weak var searchBar: UISearchBar!
    var employeesSearching = [Employee]()
    var isSearching : Bool = false
    
    @IBOutlet weak var GoogleBannerView: GADBannerView!

    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) //hide searchBar
        
        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 {
        if indexPath.row == 3 || indexPath.row == 9 || indexPath.row == 14 {
            let cellAd = tableView.dequeueReusableCell(withIdentifier: "cellAd", for: indexPath)
        
            GoogleBannerView?.adUnitID = "ca-app-pub-6043248661561548/4628935113"
            GoogleBannerView?.rootViewController = self
            GoogleBannerView?.load(GADRequest())
        
            return cellAd
        }
        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
    }
    ...
}

How do I smuggle a UITableViewCell as! AdCell randomly into the UITableView?

I mean, what should I do in cellForRowAt? I am a bit confused between all these indexed sections.


Solution

  • Firstly you need to generate a random number between 0 and your tableView Datasource array size

    let lower : UInt32 = 0
    let upper : UInt32 = array.count
    let randomIndex = arc4random_uniform(upper - lower) + lower
    

    then you need to add the Ad object in the array at the randomIndex

    array.insert(AdObject, atIndex:randomIndex)
    

    then just reload your tableView and handle the different types in cellForRow function