FIRDatabase UISearchBar string for child



新的搜索栏。

工作:

[string]" firstName"在搜索时返回正确的值。如果我有3个具有" firstName"的人,以" G"开头(例如(用3个单元格重新加载。

问题:

尽管表具有" firstName"的适当单元格值的表重新加载,但users.append(用户(返回nil和错误的名称已加载到tableView中。

帮助:

搜索完成后,如何将正确的名称加载到tableView?

这是我的代码:

func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String)->Void {
    FIRDatabase.database().reference().child("users").queryOrdered(byChild: "firstname").queryStarting(atValue: textSearched).queryEnding(atValue: textSearched+"u{f8ff}").observe(.value, with: { snapshot in
                var users = [User]()
                let user = User()
                    print(user)
                for _ in snapshot.children.allObjects as! [FIRDataSnapshot] {
                    if let dictionary = snapshot.value as? [String: AnyObject]{
                        user.lastname = dictionary["firstname"] as? String
                        users.append(user)
                    }
                }
        self.users = users
        let search = searchCell()
        search.firstName.text = user.firstname
        self.attempReloadOfTable()
    }, withCancel: nil)
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! searchCell
    var user = User()
    user = users[indexPath.row]

    if let id = user.id{
        let ref = FIRDatabase.database().reference().child("users").child(id)
        ref.observe(.value, with: { (snapshot) in
            cell.lastName.text = user.lastname
            cell.firstName.text = user.firstname
        })
    }
    return cell
}

您的问题是,在与块中的用户数据绑定之前,请返回单元格。因为在执行return cell之后将执行FIRBASE结果查询块中的代码。

我这样编辑了您的代码:

func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String)->Void {
    FIRDatabase.database().reference().child("users").queryOrdered(byChild: "firstname").queryStarting(atValue: textSearched).queryEnding(atValue: textSearched+"u{f8ff}").observe(.value, with: { snapshot in
        var users = [User]()
        for _ in snapshot.children.allObjects as! [FIRDataSnapshot] {
            if let dictionary = snapshot.value as? [String: AnyObject] {
                let user = User()
                user.lastname = dictionary["firstname"] as? String
                print(user)
                users.append(user)
            }
        }
        self.users = users
        let search = searchCell()
        search.firstName.text = user.firstname
        self.attempReloadOfTable()
    }, withCancel: nil)
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! searchCell
    let user = users[indexPath.row]
    cell.lastName.text = user.lastname
    cell.firstName.text = user.firstname
    return cell
}

希望它对您有用。

最新更新