分页不合适swift 4 Firebase

时间:2018-01-18 20:55:06

标签: ios firebase-realtime-database pagination swift4

嘿,我有一个用户可以上传帖子的litle应用程序,然后所有帖子都保存在tableview内的全局视图中,行的高度为500,这样图像足够大但是只有4个帖子然后图像开始吓坏了,帖子1和帖子4开始互相改变图像,直到细胞被正确加载但我想也许分页会有所帮助,但我没有运气所以这是我试过的现在:

var startKey: String!
func handlePagination()
{
    /*
     querying the first 3 posts in the database
     if the start key is equal to nil tis part of the code will be executed and set the last key id to the start key to fetch the following posts

     */
    let ref = Database.database().reference().child("posts").queryOrdered(byChild: "timeorder")

    if startKey == nil {
        ref.queryLimited(toLast: 3).observeSingleEvent(of: .value, with: { snapshot in
            guard let children = snapshot.children.allObjects.first as? DataSnapshot else {return}

            if snapshot.childrenCount > 0 {
                for child in snapshot.children.allObjects as![DataSnapshot]
                {
                    guard let dictionary = child.value as? [String:Any] else {return}
                    self.posts.insert(dictionary as NSDictionary , at: 0)
                }
                self.startKey = children.key
                print("firstKey is :\(self.startKey)")
                self.postsTableView.reloadData()
            }

        })
    }

    else{
        ref.queryStarting(atValue:self.startKey).queryLimited(toLast: 3).observeSingleEvent(of: .value, with: { (snapshot) in
            print("1")
            guard let children = snapshot.children.allObjects.first as? DataSnapshot else { return}
            print("2")
            if snapshot.childrenCount > 0 {
                for child in snapshot.children.allObjects as![DataSnapshot]
                {
                    if child.key != self.startKey{
                        guard let dictionary = child.value as? [String:Any] else {return}
                        self.posts.insert(dictionary as NSDictionary , at: self.posts.count)
                        print("3")
                    }
                }
                self.startKey = children.key
                print("secondKEy is :\(self.startKey)")
                self.postsTableView.reloadData()
            }
        })

    }// end of else of start key
}
/*
 using end of scroll to handle pagination if the offset is less than or equal to 150 from the current item position... calculating distance using maxoffset and the currentoffset
 */

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    let currentOffset = scrollView.contentOffset.y
    let maxOffset = scrollView.contentSize.height - scrollView.frame.size.height
    if maxOffset - currentOffset <= 150{
        print("More Posts Maybe?")
        self.handlePagination()

    }
}

此代码运行完美,实际上是获取最后一个帖子ID并从最后一个ID获取更多帖子,但代码会自动停在print("1") 我是这个Guard语句的新手,所以我尝试删除它,然后我到print("2")然后代码不起作用,我不确定这里发生了什么,但我知道我离这里不远解决方案(我希望),非常感谢任何帮助。谢谢你的时间。

0 个答案:

没有答案