我有这个数据库结构:
Users
user1
username : username1
otherdata : otherdata1
user2
username : username2
otherdate : otherdata2
我正在寻找的是当一个用户在表视图顶部使用uisearchbar时,在tableview中显示我的用户的用户名。我设法使用以下代码打印每个用户的数据:`
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
ref = Database.database().reference()
let strSearch = searchBar.text
ref.child("Users").queryOrdered(byChild: "username").queryStarting(atValue: strSearch).queryEnding(atValue: strSearch! + "\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in
for snaps in snapshot.children {
print(snaps)
}
}) { (err) in
print(err)
}
}
但是我被卡住了,因为我不知道如何只检索每个用户的用户名。有人可以告诉我该怎么做吗?
答案 0 :(得分:1)
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
ref = Database.database().reference()
let strSearch = searchBar.text
ref.child("Users").queryOrdered(byChild: "username").queryStarting(atValue: strSearch).queryEnding(atValue: strSearch! + "\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in
var fetchedList = snapshot.value as! [AnyObject]
for obj in fetchedList {
print(obj["username"] as? String)
print(obj["otherdata"] as? String)
}
}) { (err) in
print(err)
}
}
你会得到这样的回应
[{username : username1}, {username : username2}]