I am trying to fetch data from firebase while the user is typing and I want to display that data in a tableview, but when I run my code I get this error: Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeed614ff8)
This is how the structure of my database looks like.
users
uid
email
emailNotifications
username
fullName
This is what my code looks like. Instead of searching via the searchbar I just entered my own value(There is a user who has the username ginger) for this test.
//MARK: - Tableview Datasource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return findFriends(text: "gin").count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "addFriendCell", for: indexPath) as! AddFriendTableViewCell
cell.lblName?.text = findFriends(text: "gin")[indexPath.row].name
cell.lbluserName?.text = findFriends(text: "gin")[indexPath.row].username
return cell
}
func findFriends(text: String) -> [User] {
let user = User()
var userArray = [User]()
let ref = Database.database().reference()
ref.child("users").queryOrdered(byChild: "username").queryStarting(atValue: text).queryEnding(atValue: text+"\u{f8ff}").observe(.value, with: { snapshot in
for userSnapshot in snapshot.children{
let userSnapshot = userSnapshot as! DataSnapshot
guard let dictionary = userSnapshot.value as? [String: Any] else { return }
user.name = (dictionary["name"] as? String)!
user.username = (dictionary["username"] as? String)!
userArray.append(user)
}
})
tableView.reloadData()
return userArray
}
}