How can I use queryStartingAtValue in my searchcontroller to search for users?

后端 未结 2 2081
有刺的猬
有刺的猬 2021-01-28 20:56

I have previously asked a question about searching for users the most cost-efficient way (without having to load up every user in the entire database.

My code before the

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-28 21:47

    I am adding this as a separate answer as the OP has additional indirectly related questions:

    This is my entire codebase

    class ViewController: UIViewController, UISearchBarDelegate {
        @IBOutlet var searchBarOutlet: [UISearchBar]!
         override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view, typically from a nib.
            self.searchBar.delegate = self
         }
    
        var userNamesArray = [String]()
        func searchBar(_ searchBar: UISearchBar,
                       textDidChange searchText: String) {
    
            self.searchUsers(text: searchText)
        }
    
        func searchUsers(text: String) {
            self.userNamesArray = []
            if text.count > 0 {
                let ending = text + "\u{f8ff}"
                let databaseRef = self.ref.child("users")
                databaseRef.queryOrdered(byChild: "Name")
                    .queryStarting(atValue: text)
                    .queryEnding(atValue: ending)
                    .observeSingleEvent(of: .value, with: { snapshot in
                        for child in snapshot.children {
                            let childSnap = child as! DataSnapshot
                            let userName = childSnap.childSnapshot(forPath: "Name").value as! String
                            self.userNamesArray.append(userName)
                        }
                        print(self.userNamesArray) //here you would call tableView.reloadData()
                    })
            }
        }
    }
    

    That's it other than assigning self.ref to my Firebase. My structure is:

    users
      uid_0
        name: "Frank"
      uid_1
        name: "Fred"
      uid_2
        name: "Finay"
    

    etc when I type in the search field 'F' I get the following output

    ["Frank", "Fred", "Friday"]
    

    then when I type 'Fr', I get the following output

    ["Frank", "Fred"]
    

    So as you can see, it works. If it's not working in your case, you may not have your tableView connected correctly or some other issue unrelated to the search.

    Now, I am not using a tableView but simply printing name strings to the console so you would need to do a tableView.reloadData() in the place of my print statement.

提交回复
热议问题