Skip to content

Instantly share code, notes, and snippets.

@zontan
Created July 6, 2020 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zontan/00f2ce32ddbd910453684855f70e7b4f to your computer and use it in GitHub Desktop.
Save zontan/00f2ce32ddbd910453684855f70e7b4f to your computer and use it in GitHub Desktop.
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
resultsArray.removeAll()
tableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if let searchText = searchBar.text?.lowercased(), searchText != "" {
resultsArray.removeAll()
queryText(searchText, inField: "username")
} else {
// Show an error
let alert = UIAlertController(title: "Error", message: "Please enter a username.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
func queryText(_ text: String, inField child: String) {
userRef.queryOrdered(byChild: child)
.queryStarting(atValue: text)
.queryEnding(atValue: text+"\u{f8ff}")
.observeSingleEvent(of: .value) { [weak self] (snapshot) in
for case let item as DataSnapshot in snapshot.children {
//Don't show the current user in search results
if self?.currentUser?.uid == item.key {
continue
}
if var itemData = item.value as? [String:String] {
itemData["uid"] = item.key
self?.resultsArray.append(itemData)
}
}
self?.tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath)
if let userCell = cell as? UserTableViewCell {
let userData = resultsArray[indexPath.row]
userCell.displayName.text = userData["displayname"]
}
return cell
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment