swift – 一次仅检索5个用户:Firebase [如Instagram]

在过去的几天里,我一直在尝试为我的应用创建类似Instagram的Feed.更具体一点:每次用户底部更新Feed时加载新帖子(5).

我目前正在使用Firebase来存储和显示我的数据.

到目前为止我的代码看起来像这样:

var ref:FIRDatabaseReference!

    var dict = [String:Any]()
    var posts = [[String:Any]]()

   override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        ref = FIRDatabase.database().reference()

        // Do any additional setup after loading the view,typically from a nib.
    }

    override func viewDidAppear(animated: Bool) {

        loadValues()

    }

    func loadValues() {

        dict.removeAll()
        posts.removeAll()


        ref.child("posts").queryOrderedByChild("timeCreated").queryLimitedToLast(5).observeEventType(.ChildAdded) { (snapshot:FIRDataSnapshot) in

            if let timeCreated = snapshot.value!["timeCreated"] as? Int {
                self.dict["timeCreated"] = timeCreated
            }

            if let postText = snapshot.value!["postText"] as? String {
                self.dict["postText"] = postText
            }


            self.posts.append(self.dict)


            self.tableView.reloadData()

        }




    }


    func scrollViewDidScroll(scrollView: UIScrollView) {

        if (scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height {

            //tableView.tableFooterView!.hidden = true
            let pagingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
            pagingSpinner.startAnimating()
            pagingSpinner.hidesWhenStopped = true
            pagingSpinner.sizetoFit()
            tableView.tableFooterView = pagingSpinner

            //loadMore(5)

        } else {

            let pagingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
            pagingSpinner.stopAnimating()
            pagingSpinner.hidesWhenStopped = true
            pagingSpinner.sizetoFit()
            pagingSpinner.hidden = true
            tableView.tableFooterView = pagingSpinner
            tableView.tableFooterView?.hidden = true


        }


    }


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

        return posts.count

    }

    func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath)

        if let postText = posts[indexPath.row]["postText"] as? String {
            cell.textLabel!.text = postText
        }

        return cell

    }

    func loadMore(increment:Int) {

        //What should go in here?

    }

所以我想在这里做的是 – 我正在检测用户何时滚动到底部(在我的scrollViewDidScroll函数中.然后我正在显示活动指示器,并调用函数loadMore(5),其中5是金额我想要显示的新帖子.

所以这里有两个问题. timeCreated变量只是一个时间戳,我有十条记录(1-10,其中10是最新的,1是最旧的).使用我现在拥有的代码,tableView以升序视图显示数据,从5开始到10结束.

我试图通过在loadValues函数中附加dict之前简单地执行.reverse()来反转字典数组(post).因为我只想让它在顶部显示10,在底部显示5.

我遇到的第二个问题是,我似乎无法找到更新tableView(添加另外5条记录)的有效方法.我试图简单地只有一个认值为5的全局变量,然后在loadMore上加上5,然后在dict和posts上做一个removeAll() – 没有运气(tableView滚动到顶部,我不想).我也尝试使用queryLimitedTolast和queryLimitedToFirst,我最终复制了一些数据.

换句话说,我还需要确定用户实际上可以加载5个新的唯一帖子(或者例如3,如果只剩下3个唯一帖子).

有没有人对我如何处理这个问题有任何想法?

非常感谢帮助,因为我过去两天一直在努力解决这个问题.

如果您使用tableView更新您的DataSource而不是在特定索引处添加行.使用struct是一种常见的方法.
struct dataS {

var postData : String!
var index_Initial : Int!

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

}

>声明一个dataSourceS类型的数组

var datafeed= [dataS]()

>为了知道你已经审阅了多少帖子,你需要在帖子节点本身保留每个帖子的索引.这可以通过计算post节点中的子节点数并将其递增1来完成.或者创建完整的单独节点

noOfPosts: 100,//Lets say there are 100 posts in your DB 

 Posts : {
  Post1:{


     text : asdasdasd,index : 12               

      },Post2:{


     text : asdasddasdasd,index : 13              

      },.....
 }

您的最终代码将如下所示: –

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
  }

}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...