首页 > 解决方案 > 如何获取数据库中的所有用户“用户名”?

问题描述

我正在为我的应用程序创建一个搜索页面,允许用户相互搜索。我遇到的问题是我只能搜索我当前登录的用户。(注意我做了另外 8 个假用户

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

//let uid = Auth.auth().currentUser?.uid

var ref = Database.database().reference().child("users").child("\(Auth.auth().currentUser!.uid)")  

var filteredData = [UserModel]()

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.dataSource = self
    searchBar.delegate = self
    //filteredData = data

    ref.queryOrderedByValue().observeSingleEvent(of: .value) { (snapshot) in
        if let userDict = snapshot.value as? [String : AnyObject] {
            let userSearch = userDict["username"] as? String

            self.filteredData.append(UserModel(NameDisplay: userSearch))
            self.tableView.reloadData()

        }
    }

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "SearchCell", for: indexPath) as UITableViewCell
    cell.textLabel?.text = filteredData[indexPath.row].NameDisplay
    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredData.count
}

}

我期望每个用户都显示在 Tableview 中,然后我可以搜索。正在发生的只是当前登录的用户正在显示

标签: swiftfirebasefirebase-realtime-database

解决方案


您的

var ref = Database.database().reference().child("users").child("\(Auth.auth().currentUser!.uid)")  

正在从 users 集合中获取特定的子对象,如果您只获取 users 对象,那么您将有权访问可以搜索其他用户的整个子对象集合。


推荐阅读