Hey i've got a litle app that users can upload posts and and then all posts are saved in a global view inside a tableview with the height of the rows at 500 so that the images are big enough but when there is only 4 posts then the images starts to freak out and post 1 and post 4 is starting to change images with each other untill the cell is propperly loaded but i thought maybe pagination would help but i got no luck so for this is what i have tryed for now:
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()
}
}
this code runs perfectly and is actually getting the last post id and is fetching more posts from that last id but the code stops automaticlly at print("1")
i'm new to this Guard statements so i tryed removing it and i got to print("2")
and then the code doesnt work ferther i'm not exactly sure what is going on here but i know i'm not far from the solution (i hope), Any help is Greatly appreciated. thanks for your time.