我正在尝试实现搜索栏,以便根据搜索查询填充表格视图。我只是在这里寻找用户名。
数据结构:
"Users"
-"UID"
-"Username"
我正在查询运行搜索栏中输入的文字的查询。我可以很好地打印搜索结果,所以我知道他们会回来。但是,我无法从查询结束中突破数据并且不知道该怎么做
我尝试构建一个内部数组,然后只设置外部数组,但它总是包含零值。我知道我的for循环正在运行,我知道正在返回值。他们只是没有得救。
self.filteredNameList = []
let searchText = searchText.lowercased()
let userQuery = ref.queryOrdered(byChild: "username").queryStarting(atValue: searchText)
userQuery.observeSingleEvent(of: .value, with: { (snapshot) in
for snap in snapshot.children {
let userSnap = snap as! FIRDataSnapshot
let userDict = userSnap.value as! [String: AnyObject]
let name = userDict["username"] as! String
self.filteredNameList.append(name)
}
self.tableView.reloadData()
print("Inside closure: \(self.filteredNameList)")
})
print("Outside closure: \(self.filteredNameList)")
}
我该怎么办?谢谢 - 基南
答案 0 :(得分:1)
这是一个经过测试的例子
给出一个firebase结构
users
uid_0
name: "bill"
uid_1
name: "leroy"
uid_2
name: "frank"
uid_3
name: "leon"
我们希望返回以' le'开头的所有节点并将它们存储在一个数组中
var namesArray = [String]() //note this is stored outside the function so other
//functions can access it.
func getSomeLe() {
self.namesArray = [] //init it any time this func is called.
let usersRef = ref.child("users")
let queryRef = usersRef.queryOrdered(byChild: "name").queryStarting(atValue: "le")
queryRef.observeSingleEvent(of: .value, with: { (snapshot) in
for snap in snapshot.children {
let userSnap = snap as! FIRDataSnapshot
let uid = userSnap.key
let userDict = userSnap.value as! [String:AnyObject]
let name = userDict["name"] as! String
self.namesArray.append(name)
}
print(self.namesArray)
})
}
将数据存储在数组中并打印
["乐华""莱昂"]