Search code examples
iosswiftxcodeadmobtableview

How to display ad in uitableview admob swift?


I am very new to admob nativeads and I checked every tutorial online on how to add ads in tableview, but I did not find any luck This is the code I have so far in my cellforrowat function:

let cell = Bundle.main.loadNibNamed("NativeAdTableViewCell", owner: self, options: nil)?.first as! NativeAdTableViewCell
        
        print("ad = \(ad == nil)")
        cell.adTitle.text = ad?.headline
        cell.adSubtitle.text = ad?.body
        cell.img.image = ad?.icon?.image
        cell.selectionStyle = UITableViewCell.SelectionStyle.none
        return cell

Other code:

func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADUnifiedNativeAd) {
    nativeAd.delegate = self
    ad = nativeAd
}

Thank you in advanced


Solution

  • You can simply add an empty element in your tableView dataSource array when receive your add like below:

    func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADUnifiedNativeAd {
       nativeAd.delegate = self
       self.yourDataSource.insert("", at: 0) // add empty element in where you show your ads
       ad = nativeAd
       yourTableView.reloadData() 
    }
    

    After that your tableViewCell look like :

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let data = self.yourDataSource[indexPath.row]as? [String]
        if data == nil {
            
            let nativeAd = self.ad //Your native ads object
            nativeAd.rootViewController = self
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "nativecell", for: indexPath)as! nativecell // nativecell is your native ad cell
            let adView = cell.adview
            adView!.nativeAd = nativeAd
            cell.headline.text = nativeAd.headline
            cell.icon.image = nativeAd.icon?.image
            cell.body.text = nativeAd.body
            cell.action.isUserInteractionEnabled = false
            cell.action.setTitle(nativeAd.callToAction, for: UIControl.State.normal)
            return cell
            
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "regularCell", for: indexPath)as! regularCell
            
            return cell
        }
    }
    

    Thanks