Hey Brian,
love your videos! Love this course.
I have found that for large user datasets, its very ineffictient to fetch them all and then filter the array. It's definitly enough for this course!
For everyone that is interested in handling a bigger amount of Users:
It would be nicer, if we could search "in the database" and then fetch every user, that fits our searchText.
So, it would user this function instead of fetchUser():
func fetchUserWithUsername(searchText: String) {
filteredUsers = [User]()
let userRef = Database.database().reference().child("users").queryOrdered(byChild: "username").queryStarting(atValue: searchText).queryEnding(atValue: searchText+"\u{f8ff}")
userRef.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionaries = snapshot.value as? [String: Any] else { return }
dictionaries.forEach({ (key, value) in
guard let userDictionary = value as? [String: Any] else { return }
let user = User(uid: key, dictionary: userDictionary)
let isContained = self.filteredUsers.contains(where: { (containedUser) -> Bool in
return user.id == containedUser.id
})
if !isContained {
self.filteredUsers.append(user)
self.collectionView?.reloadData()
}
})
}) { (err) in
print("failed to fetch searched User", err)
}
}
I use it in func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String), every time the text isn't empty.
If the searchBar is empty, maybe it would be nice to fetch the first 10 user in the database, so you could use a different DatabaseReference:
Database.database().reference().child("users").queryLimited(toFirst: 10)
Maybe this will help some people :)
Kindest Regards,
Luca