I am fetching the current user's friends and storing the users in an array which gets displayed in a collection view. The friends collection view is on my home view controller which means it always remains in the users stack.
My problem is, if the user adds or removes friends via the users profile page and then navigates back to the home view, I have to refetch the data and refresh the collection view in viewWillAppear
. This makes the app costly for data and I definitely feel this is not the most efficient way.
I know that Firebase allows me to setup observers, however I am not too sure on the best way to do this without receiving massive loads of data.
Here is the way I currently fetch the user's friends
func fetchFriends() {
let userID = Auth.auth().currentUser?.uid
var tempFriend = [UserClass]()
self.usersArray.removeAll()
collectionView.reloadData()
let friendRef = self.databaseRef.child("users").child(userID!).child("Friends")
friendRef.queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
let friendID = "\(snapshot.value!)"
let usersRef = self.databaseRef.child("users")
usersRef.observeSingleEvent(of: .value, with: { (users) in
for user in users.children {
let friend = UserClass(snapshot: user as! DataSnapshot)
if friendID == friend.uid {
tempFav.append(friend)
}
}
self.usersArray = tempFav
self.collectionView.reloadData()
if self.usersArray.count == 0 {
self.noDataLabel.text = "You have no friends!"
self.noDataLabel.isHidden = false
} else {
self.noDataLabel.text = "Loading..."
self.noDataLabel.isHidden = true
}
})
})
}
This gets called in the user's viewWillAppear
To make this question as clear as possible, what is the best way to refresh the user's friends without needing to fetch the entire list again every time the view appears.