OGeek|极客世界-中国程序员成长平台

标题: ios - Firebase 将用户检索到 tableView [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:24
标题: ios - Firebase 将用户检索到 tableView

我在将用户数据检索到 TableView 时遇到问题,我的代码有效,并且我在单元格中看到用户的姓名,但 问题是当其中一个用户对其个人资料进行任何更改时,他的单元格将重复

firebase 结构:

enter image description here

ViewDidLoad 和单元格行:

override func viewDidLoad() {
    super.viewDidLoad()

    ref = FIRDatabase.database().reference()

    USER_REF.keepSynced(true)
    friends_REF.keepSynced(true)


    showUsersObserver {}


}


func 

tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.friendList.count

    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let Cell:TableViewCellx = tableView.dequeueReusableCell(withIdentifier: "mainCell") as! TableViewCellx



        Cell.name.text = self.friendList[indexPath.row].displayname
return(Cell)
}

这是在 friend 子结构中获取用户的 key 。

 func showUsersObserver(_ update: @escaping () -> Void) {
    CURRENT_USER_FRIENDS_REF.observe(.value, with: { (snapshot) in
        self.friendList.removeAll()


        let keys = snapshot.children
        while let rest = keys.nextObject() as? FIRDataSnapshot {



            self.getUser(rest.key, completion: { (user) in
                self.friendList.append(user)

                print(self.friendList.count) // This increase each time when user changing his name! or any changes hits his profile.

                DispatchQueue.main.async {
                    self.tableview.reloadData()
                }

                update()
            })

        }



        // If there are no children, run completion here instead
        if snapshot.childrenCount == 0 {
            update()
        }
    })
}

这是获取他们的个人资料数据:

func getUser(_ userID: String, completion: @escaping (User) -> Void) {
    USER_REF.child(userID).observe(.value, with: { (snapshot) in

        guard let dictionary = snapshot.value as? [String: Any] else {
            return
        }



        let id = dictionary["uid"] as? String
        let email = dictionary["email"] as? String
        let DisplayName = dictionary["displayname"] as? String




        completion(User(userEmail: email!, userID: id!, userDisplayName: DisplayName!))



    })
}

还有 friend 列表:

class User {

var uid: String!
var displayname: String!
var email: String!


init(userEmail: String, userID: String, userDisplayName: String) {

    self.email = userEmail
    self.uid = userID
    self.displayname = userDisplayName

    }
}

当我在 friend child 中添加\删除键时,我看到我的 tableView 中的更新效果很好,但是如果其中一个键更改了他的名字,它将显示他的旧\新单元格,因此他的名字重复了。



Best Answer-推荐答案


保持 tableView 中每一行的唯一标识符与用户名相关联。

当用户更新时,从用户列表中获取数据,然后更新该特定项目。

您可以使用用户 key 作为唯一标识符

谢谢

关于ios - Firebase 将用户检索到 tableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45434957/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4