【发布时间】:2017-08-12 00:14:10
【问题描述】:
我有一个函数可以从我的 Firebase 数据库中获取帖子并填充集合视图,一次 15 个帖子使用:
ref.child("posts").queryOrderedByKey().queryLimited(toLast: 15).observeSingleEvent(of: .value, with: { (snap) in
现在我希望每次用户到达屏幕底部时获取接下来的 15 个帖子。在我的cellForItem 方法中,我试图检查是否已到达页面底部,如果已到达,则在其停止的位置加载接下来的 15 个帖子。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath) as! PostCell
cell.postImage.loadImageUsingCacheWithUrlString(posts[indexPath.row].pathToImage)
cell.postID = posts[indexPath.row].postID
cell.postImage.contentMode = UIViewContentMode.scaleAspectFill
if indexPath.row == posts.count - 1
{
fetchPosts()
}
return cell
}
我只是不知道如何指定在加载接下来的 15 个帖子时,它们需要从最后 15 个停止的地方开始,而不是再次获取数据库中的所有帖子。
这是整个fetchPosts()函数:
func fetchPosts() {
let ref = FIRDatabase.database().reference()
ref.child("users").queryOrderedByKey().observe(.value, with: { snapshot in
let users = snapshot.value as! [String : AnyObject]
for (_, value) in users {
if let uid = value["uid"] as? String {
if uid == FIRAuth.auth()?.currentUser?.uid {
if let followingUsers = value["following"] as? [String : String] {
for (_, user) in followingUsers {
self.following.append(user)
}
}
self.following.append(FIRAuth.auth()!.currentUser!.uid)
ref.child("posts").queryOrderedByKey().queryLimited(toLast: 15).observeSingleEvent(of: .value, with: { (snap) in
for postSnapshot in snap.children.allObjects as! [FIRDataSnapshot] {
let value = postSnapshot.value as! [String : AnyObject]
if let userID = value["userID"] as? String {
for each in self.following {
if each == userID {
let posst = Post()
if let poster = value["poster"] as? String, let likes = value["likes"] as? Int, let pathToImage = value["pathToImage"] as? String, let postID = value["postID"] as? String {
posst.poster = poster
posst.likes = likes
posst.pathToImage = pathToImage
posst.postID = postID
posst.userID = userID
if let people = value["peopleWhoLike"] as? [String : AnyObject] {
for (_, person) in people {
posst.peopleWhoLike.append(person as! String)
}
}
posts.append(posst)
}
}
}
self.collectionView.reloadData()
}
}
})
ref.removeAllObservers()
}
}
}
})
}
我可以在此处添加/更改什么以确保每次到达页面底部时按顺序加载 15 个帖子?
【问题讨论】:
-
[这篇文章](stackoverflow.com/questions/37430881/swift-ios-firebase-paging/…) 回答了这个问题。
标签: ios swift firebase firebase-realtime-database uicollectionview