Random ads between cells in a Table View

Asked

Viewed 79 times

2

I’m trying to insert Ads totally random between cells within a UITableView. That’s kind of what I want:

Randomly Ads

So is mine Table View Controller:

import UIKit
import GoogleMobileAds

class Page1: UITableViewController, UISearchBarDelegate, GADBannerViewDelegate {
    ...
    ...
    ...
    @IBOutlet weak var GoogleBannerView: GADBannerView!

    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
        }
    }

    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
    }
    ...
    ...
    ...
}

I wish someone could explain to me what I should do at cellForRowAt so that I could add the Ads. Because in the middle of the Indexed sections I’m kind of confused.


EDIT

This is my Tableviewcell class currently:

import UIKit

class TableViewCell1: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var positionLabel: UILabel!

}
  • 1

    Creates another cell with another Identifier pro ad. Returns one extra cell per session. Then checks if the indexPath.row == 0 and if it is use add cell instead of the other.

  • I was able to display the cells the way I wanted. But I can’t insert a GADBannerView then... I don’t know where I’m going wrong. I edited my question for you to see how it turned out. I can’t associate the @IBOutlet GoogleBannerView to the Main.Storyboard.

  • 1

    You have to create a subclass of UITableViewCell, use this class for the ad cell and this is where you will add the outlet and associate to the storyboard.

  • Excuse the amateurism, but how do I create this subclass? I Googled but found nothing useful. I also edited my question to show you the current structure of TableViewCell.

  • 1

    Dude, you’ll have to look for tutorials on how to use Uitableview and train a little. That’s the basics, and it’s a lot for me to explain here.

  • Don’t worry, you’ve helped me a lot! I think I got it here. Fight

  • 1

    Good luck out there. :)

Show 2 more comments

1 answer

1


To insert the Randomic ADS, I indicate that you modify the data array you use to mount the tableview, before displaying the tableview.

For this, Voce could insert the ADS in your data array... or inside the method tableView(tableView: UITableView, numberOfRowsInSection section: Int) together with a variable isAdsAdicionadas; or in some method called by your code BEFORE the numberOfRowsInSection, at the time of instantiation of the screen (I particularly prefer this approach)

From what I saw the array you’re using for this is the matches

So I could do more or less that:

Create attribute isAdsAdicionadas and in the numberOfRowsInSection check variable state, if false, call the method inserirADSRandomicamente:

let isAdsAdicionadas: Bool = false

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if(isAdsAdicionadas == false){

        self.inserirADSRandomicamente()
    }

    isAdsAdicionadas = true

    return matches.count
}

func inserirADSRandomicamente(){

    var indiceRandomico: Int!
    var arrayIndiceRandomico:[Int] = []
    let numeroMaximoDeADS = 3
    var contador = 0

    func randomizar(){

        indiceRandomico = Int(arc4random_uniform(UInt32(matches.count)))
        if(contador <= numeroMaximoDeADS){
            if(arrayIndiceRandomico.contains(indiceRandomico) == true){
                randomizar()
            }
            else{
                let objetoADS = "OBJETO ADS"
                matches.insert(objetoADS, at: indiceRandomico)
                arrayIndiceRandomico.append(indiceRandomico)
                contador += 1
                randomizar()
            }
        }
        else{
            return
        }
    }

    randomizar()
}

From there, Voce already has the array with the random ADS. Just treat the cases of being ADS or not, in the method func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

You can add more logics in the method randomizar(), if you do not want to display two ADS in a row, for example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.