【发布时间】:2017-01-18 17:30:11
【问题描述】:
在过去的几天里,我一直在尝试为我的应用创建类似 Instagram 的提要。更具体地说:每次用户从底部更新提要时加载新帖子 (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) where 5是我想要显示的新帖子的数量。
所以这里我有两个问题。 timeCreated 变量只是一个时间戳,我有十条记录(1-10,其中 10 是最新的,1 是最旧的)。使用我现在拥有的这段代码,tableView 以升序视图显示数据,从 5 开始到 10 结束。
我试图通过在 loadValues 函数中附加字典之前简单地执行 .reverse() 来反转字典数组(post)。因为我只是希望它在顶部显示 10,在底部显示 5。
我遇到的第二个问题是,我似乎真的找不到更新 tableView 的好方法(添加另外 5 条记录)。我试图简单地只拥有一个默认值为 5 的全局变量,然后在 loadMore 上简单地将其加 5,然后在 dict 和帖子上执行 removeAll() - 没有运气(tableView 滚动到顶,我不想)。我还尝试同时使用 queryLimitedTolast 和 queryLimitedToFirst,最终复制了一些数据。
因此,换句话说,我还需要检查用户实际上是否可以加载 5 个新的唯一帖子(或者例如 3,如果只剩下 3 个唯一帖子)。
有人对我将如何处理这个问题有任何想法吗?
非常感谢您的帮助,因为过去两天我一直在努力解决这个问题。
【问题讨论】:
-
PS:如果有必要,我很乐意分享我的 Firebase 数据结构。
-
我想我解决了。看讨论,chat.stackoverflow.com/rooms/123147/…
标签: swift uitableview firebase firebase-realtime-database updates