使用Firebase在UITableView中使用搜索

时间:2019-04-10 10:04:25

标签: ios swift firebase uitableview firebase-realtime-database

我有一个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)
        }
    }

observePostsobserveSearchPosts之间的唯一区别是数据库参考行:

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")

1 个答案:

答案 0 :(得分:0)

从firebase获取所有数据,然后在本地数组中使用搜索。 然后重新加载tableview