Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了swift – 一次仅检索5个用户:Firebase [如Instagram]大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

在过去的几天里,我一直在尝试为我的应用创建类似Instagram的Feed.更具体一点:每次用户从底部更新Feed时加载新帖子(5). 我目前正在使用Firebase来存储和显示我的数据. 到目前为止我的代码看起来像这样: var ref:FIRDatabaseReference! var Dict = [String:Any]() var posts = [[String:An
在过去的几天里,我一直在尝试为我的应用创建类似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 @R_727_10586@lNoOfPost : 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.@R_727_10586@lNoOfPost = 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("customcatell") as! customTableViewCell
    if DataFeed.count > 0{
    cell.poatLabel.text = dataFeed[indexPath.row].postData
    }
    return cell
}

func loadMore(){

    let initialFeedCount : Int = dataFeed.count

    if @R_727_10586@lNoOfPost - initialFeedCount - 4 > 0{

    FIRDatabase.database().reference().child("Posts").queryorderedByChild("index").queryStarTingAtValue(@R_727_10586@lNoOfPost - initialFeedCount - 4).queryEndingAtValue(@R_727_10586@lNoOfPost - 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 @R_727_10586@lNoOfPost - initialFeedCount - 4 <= 0{


        FIRDatabase.database().reference().child("Posts").queryorderedByChild("index").queryStarTingAtValue(0).queryEndingAtValue(@R_727_10586@lNoOfPost - 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
  }

}

大佬总结

以上是大佬教程为你收集整理的swift – 一次仅检索5个用户:Firebase [如Instagram]全部内容,希望文章能够帮你解决swift – 一次仅检索5个用户:Firebase [如Instagram]所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。