Reputation: 1127
with this code i am able to get a snapshot of my database and load the data into a tableView. However, when i try to make a change to the online database i get duplicated cells that apply the change instead of the normal cells applying this change.
// Create reference to databse
ref = Database.database().reference()
// Retrieve data from firebase database and listen for changes
ref.child("Clubs").observe(.value, with: { (snapshot) in
print("clubs: \(snapshot)")
if(snapshot.exists()) {
let array:NSArray = snapshot.children.allObjects as NSArray
for obj in array {
let snapshot:DataSnapshot = obj as! DataSnapshot
if let childSnapshot = snapshot.value as? [String : AnyObject] {
print("myClubs: \(childSnapshot)")
if let clubName = childSnapshot["name"] as? String, let banner = childSnapshot["bannerImage"] as? String {
print(clubName)
print(banner)
let club = Club(name: clubName, image: banner)
print("new club success: \(club)")
self.nightClubs.append(club)
}
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
})
Upvotes: 0
Views: 39
Reputation: 7546
Whenever any value in Clubs
changes, you're executing the code inside the listener. The code appends the clubs to the nightClubs
array, but doesn't clear it. You need to empty the array before repopulating:
// Retrieve data from firebase database and listen for changes
ref.child("Clubs").observe(.value, with: { (snapshot) in
print("clubs: \(snapshot)")
self.nightClubs.removeAll() // empty array before adding values
...
Upvotes: 2