I'm working with Observes from Firebase and CollectionViews to fill my cells with information. All my data is displayed correctly on my collectionView, the problem appears when I finish updating the values from my post in the Firebase, the app starts scrolling up after the update and as well duplicates the values in the cells.
I already try to call reloadData in most of the common functions that I am using but keeps scrolling to the top. The duplicated cells only occurs when I took a photo with my camera.
var postVibe = [PostVibe]()
fileprivate func fetchPostWithUser() {
guard let uid = Auth.auth().currentUser?.uid else { return }
guard let city = CityState.currentCity else { return }
let ref = Database.database().reference().child("vibes").child("city").child(city)
ref.observe(.value, with: { (snapshot) in
self.postVibe.removeAll()
if snapshot.exists() {
self.collectionView.refreshControl?.endRefreshing()
guard let vibeDic = snapshot.value as? [String: Any] else { return }
vibeDic.forEach({ (key, value) in
guard let newDic = value as? [String: Any] else { return }
var vibe = PostVibe(postId: key, dictionary: newDic)
Database.database().reference().child("votes").child(vibe.postId).child(uid).observe(.value, with: { (snapshot) in
if snapshot.exists() {
if let value = snapshot.value as? Int, value == 1 {
vibe.hasVoteUp = true
vibe.hasVoteDown = false
} else {
vibe.hasVoteUp = false
vibe.hasVoteDown = true
}
} else {
}
self.postVibe.append(vibe)
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}, withCancel: { (err) in
print("Failed to fetch Votes: ", err)
})
})
} else {
self.collectionView.refreshControl?.endRefreshing()
}
}) { (err) in
print("Failed to fetch Vibes: ", err)
}
}
What I want to expect from my code is to be able to remove the old data and just displayed the new one included the ones that had been updated, with the duplicated cells I expect to not show 6 cells when I need only 3 that in the database.
This is what I had used for tableView scrolling , you can use same for collectionView if possible.
let contentOffset = tableView.contentOffset
tableView.reloadData()
tableView.setContentOffset(contentOffset, animated: false)