Native Ads in TableView with Data from Server

240 views
Skip to first unread message

Henry Agyei

unread,
May 27, 2017, 7:25:57 PM5/27/17
to Google Mobile Ads SDK Developers
I am having a problem with the Native Ads Layout and changing it from the hard coded json data to data from Server
The issue is around the count of data in the array. As the server appends data into the array as the app loads and user scrolls down, the addNativeExpressAds function does not run correctly and appears to loop through func.
Please advise on how to fix this

Thanks

v



class controller: UICollectionViewController, UICollectionViewDelegateFlowLayout,  GADNativeExpressAdViewDelegate {

    

    var collectionViewItems = [AnyObject]()

    var adsToLoad = [GADNativeExpressAdView]()

    var loadStateForAds = [GADNativeExpressAdView: Bool]()

    let adUnitID = "ca-app-pub-3710924718089875/7954396940"

    let adInterval = 2


    private let cellId = "cellId"

    let adMobCellId = "adMobCellId"

    let adViewHeight = CGFloat(350)


    var testimonials = [Testimonials]()

    

    

    override func viewDidLoad() {

        super.viewDidLoad()

      

        

        collectionView?.registerClass(LoaderFeed, forCellWithReuseIdentifier: cellId)

        collectionView?.registerClass(AdMobCell.self, forCellWithReuseIdentifier: adMobCellId)

        

                

        fetchTestimonials()

adNativeExpressAds

        preloadNextAd()

        

    }

    


    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

        return 1

    }

    

    

    func collectionView(collectionView: UICollectionView,

                        layout collectionViewLayout: UICollectionViewLayout,

                               sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        let height = (view.frame.width) * 9 / 16

        

        if let collectionViewItem = collectionViewItems[indexPath.item] as? GADNativeExpressAdView {

            let isAdLoaded = loadStateForAds[collectionViewItem]

            return isAdLoaded == true ? CGSize(width: collectionView.frame.width, height: 350) :  CGSize(width: 0, height: 0)

        } else {

            return CGSize(width: collectionView.frame.width, height: 350)

        }

    }


    

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        print(collectionViewItems.count)

        return collectionViewItems.count

    }

    

        func loadFromServer() {


        

        let ref = FIRDatabase.database().reference().child("loadData")

        ref.queryOrderedByChild("reverseTimestamp").observeEventType(.ChildAdded, withBlock: { (snapshot) in

            guard let dictionary = snapshot.value as? [String: AnyObject] else { return}

            

            let testimonial = LoadServer()

            testimonial.id = dictionary["id"] as? String


            

            self.tableViewItems.append(testimonial)

            self.tableView?.reloadData()

            }, withCancelBlock: nil)

    }



    

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        print(collectionViewItems.count)

        if let nativeExpressAdView = collectionViewItems[indexPath.item] as? GADNativeExpressAdView {

            let reusableAdCell = collectionView.dequeueReusableCellWithReuseIdentifier(adMobCellId, forIndexPath: indexPath) as! AdMobCell

            

            // Remove previous GADNativeExpressAdView from the content view before adding a new one.

            for subview in reusableAdCell.contentView.subviews {

                subview.removeFromSuperview()

            }

            

            reusableAdCell.contentView.addSubview(nativeExpressAdView)

            // Center GADNativeExpressAdView in the table cell's content view.

            nativeExpressAdView.center = reusableAdCell.contentView.center

            

            let videoOptions = GADVideoOptions()

            videoOptions.startMuted = false

            nativeExpressAdView.setAdOptions([videoOptions])

            

            return reusableAdCell

            

        }

        else {

            

            let testimonial = collectionViewItems[indexPath.item]

            

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as! TestimonialsFeed

     

return cell

        }

    }

    


    


    func nativeExpressAdViewDidReceiveAd(nativeExpressAdView: GADNativeExpressAdView) {

        loadStateForAds[nativeExpressAdView] = true

        preloadNextAd()

    }

    

    func nativeExpressAdView(nativeExpressAdView: GADNativeExpressAdView,

                             didFailToReceiveAdWithError error: GADRequestError) {

        print("Failed to receive ad: \(error.localizedDescription)")

        preloadNextAd()

    }



//***Problem here in the code loops through continuously and does not load page 

    func addNativeExpressAds() {

        var index = adInterval

        print(collectionViewItems.count)

        collectionView?.layoutIfNeeded()

        while index < collectionViewItems.count {

            let adSize = GADAdSizeFromCGSize(

                CGSize(width: (collectionView!.contentSize.width), height: adViewHeight))

            guard let adView = GADNativeExpressAdView(adSize: adSize) else {

                print("GADNativeExpressAdView failed to initialize at index \(index)")

                return

            }

            adView.adUnitID = adUnitID

            adView.rootViewController = self

            adView.delegate = self

            

            collectionViewItems.insert(adView, atIndex: index)

            //adsToLoad.append(adView)

            loadStateForAds[adView] = false

            

            index += adInterval


        }

    }

    

    

    func preloadNextAd() {

        if !adsToLoad.isEmpty {

            let ad = adsToLoad.removeFirst()

            ad.loadRequest(GADRequest())

        }

    }

    


    

   

Joshua Lagonera (Mobile Ads SDK Team)

unread,
May 29, 2017, 1:46:23 AM5/29/17
to Google Mobile Ads SDK Developers
Hi Henry,

The issue might be caused by how Firebase Database handles its .childAdded callback, since it is being called per child added, which may cause your CollectionView items array to have unexpected elements in certain indexes. 

That said, since your concern is more of an implementation issue rather than our SDK, I would suggest you try and open a new thread over at StackOverflow for additional assistance on this.

Regards,
Joshua Lagonera
Mobile Ads SDK Team
Reply all
Reply to author
Forward
0 new messages