Retrieve only 5 users at a time :Firebase [like Instagram]

浪子不回头ぞ 提交于 2019-11-27 09:21:32

If you are using tableView update your DataSource instead of adding a row at a particular index. using struct is a common aproach.

struct dataS {

var postData : String!
var index_Initial : Int!

init(post : String!, ind : Int!)
{
 self.postData = post
 self.index_Initial = ind
  }

}
  • Declare an array of type dataSourceS

         var dataFeed= [dataS]()
    
  • For knowing that how many posts you have already retrived , you need to keep the index of each post in the the post node itself.Which can be done by counting the no of children in the post node and incrementing it by one.Or creating a complete separate node of

    noOfPosts: 100, //Lets say there are 100 posts in your DB 
    
     Posts : {
      Post1:{
    
    
         text : asdasdasd,
         index : 12               
    
          },
    
       Post2:{
    
    
         text : asdasddasdasd,
         index : 13              
    
          },.....
     }
    

Your final code will look something like this:-

 import UIKit
import Firebase

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var dataFeed = [dataS]()
let pagingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
var totalNoOfPost : Int!



@IBOutlet weak var customTableView: UITableView!




override func viewDidLoad() {
    super.viewDidLoad()

    customTableView.delegate = self
    customTableView.dataSource = self
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    FIRDatabase.database().reference().child("Posts").observeSingleEventOfType(.Value, withBlock: {(snap) in

        if let postDict = snap.value as? [String:AnyObject]{

             self.totalNoOfPost = postDict.count

                self.loadMore()
        }
    })

}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataFeed.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = customTableView.dequeueReusableCellWithIdentifier("customCell") as! customTableViewCell
    if dataFeed.count > 0{
    cell.poatLabel.text = dataFeed[indexPath.row].postData
    }
    return cell
}

func loadMore(){

    let initialFeedCount : Int = dataFeed.count

    if totalNoOfPost - initialFeedCount - 4 > 0{

    FIRDatabase.database().reference().child("Posts").queryOrderedByChild("index").queryStartingAtValue(totalNoOfPost - initialFeedCount - 4).queryEndingAtValue(totalNoOfPost - initialFeedCount).observeEventType(.Value, withBlock: {(recievedSnap) in

        if recievedSnap.exists(){

        for each in recievedSnap.value as! [String:AnyObject]{
            let temp = dataS.init(post: each.1["text"] as! String, ind : each.1["index"] as! Int)
            self.dataFeed.insert(temp, atIndex: 5 * Int(self.dataFeed.count/5))
            self.dataFeed.sortInPlace({$0.index_Initial > $1.index_Initial})
               if self.dataFeed.count == initialFeedCount+5{
                self.dataFeed.sortInPlace({$0.index_Initial > $1.index_Initial})
                self.customTableView.reloadData()

            }
          }

         }
        }, withCancelBlock: {(err) in

            print(err.localizedDescription)


      })

    }else if totalNoOfPost - initialFeedCount - 4 <= 0{


        FIRDatabase.database().reference().child("Posts").queryOrderedByChild("index").queryStartingAtValue(0).queryEndingAtValue(totalNoOfPost - initialFeedCount).observeEventType(.Value, withBlock: {(recievedSnap) in

            if recievedSnap.exists(){

            for each in recievedSnap.value as! [String:AnyObject]{

                let temp = dataS.init(post: each.1["text"] as! String, ind : each.1["index"] as! Int)

                self.dataFeed.insert(temp, atIndex: 5 * Int(self.dataFeed.count/5))
                self.dataFeed.sortInPlace({$0.index_Initial > $1.index_Initial})
                if self.dataFeed.count == initialFeedCount+4{
                   self.dataFeed.sortInPlace({$0.index_Initial > $1.index_Initial})
                    self.customTableView.reloadData()
                        self.pagingSpinner.stopAnimating()
                }
              }
            }else{

            self.pagingSpinner.stopAnimating()
            }

            }, withCancelBlock: {(err) in

                print(err.localizedDescription)


        })
    }
}

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if (indexPath.row + 1) == dataFeed.count {
        print("Displayed the last row!")


                    pagingSpinner.startAnimating()
                    pagingSpinner.hidesWhenStopped = true
                    pagingSpinner.sizeToFit()
                    customTableView.tableFooterView = pagingSpinner
                    loadMore()
    }
}


}


struct dataS {

var postData : String!
var index_Initial : Int!

init(post : String!, ind : Int!)
{
 self.postData = post
 self.index_Initial = ind
  }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!