我有一个UITableView
,其中root->Data
节点的所有详细信息都已成功获取。我正在尝试实现SearchController
来过滤数据,但是它似乎无法获取搜索结果并绑定到UITableView
。
我的Firebase JSON结构如下:
"Data" : {
"01" : {
"priority" : 2,
"search" : "school centre",
"title" : "School Centre"
},
这是updateSearchResults
中的代码:
func updateSearchResults(for searchController: UISearchController) {
filterContent(searchText: self.searchController.searchBar.text!.lowercased())
}
func filterContent(searchText:String)
{
if (searchText.count == 0){
observePosts()
} else {
print(searchText)
observeSearchPosts(searchText: searchText)
}
}
observePosts
和observeSearchPosts
之间的唯一区别是数据库参考行:
func observeSearchPosts(searchText: String) {
let postsRef = Database.database().reference().child("Data").queryOrdered(byChild: "search").queryStarting(atValue: searchText)
print(postsRef)
postsRef.observe(.value, with: { snapshot in
var tempPosts = [Post]()
for child in snapshot.children{
if let childSnapshot = child as? DataSnapshot,
let dict = childSnapshot.value as? [String:Any],
let title = dict["title"] as? String,
let logoImage = dict["image"] as? String,
let url = URL(string:logoImage),
let address = dict["address"] as? String,
let contact = dict["contact"] as? String,
let description = dict["description"] as? String{
let userProfile = UserProfile(title: title, photoURL: url)
let post = Post(id: childSnapshot.key, title: userProfile, description: description, image: userProfile, address: address, contact: contact)
print(post)
tempPosts.append(post)
}
}
self.posts = tempPosts
self.tableView.reloadData()
})
}
在observePosts
中,数据库引用为let postsRef = Database.database().reference().child("Data").queryOrdered(byChild: "priority")
。
答案 0 :(得分:0)
从firebase获取所有数据,然后在本地数组中使用搜索。 然后重新加载tableview