2017-08-01 65 views
2

我有麻烦,检索用户数据到TableView,我的代码工作,我看到用户在单元格中他们的名字,但问题是当其中一个用户已经对他们的个人资料进行了任何更改他的单元格将重复Firebase检索用户到tableView

火力结构:

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

这让用户在朋友的孩子结构键。

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



    }) 
} 

而且好友列表:

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 

    } 
} 

当我添加\在朋友的孩子取下钥匙,我看到我的tableView作品更新好,但如果其中一个键已经改变了他的名字,它会显示他的旧\新单元,所以他的名字重复。

+0

为什么没有aswers;○ – Sam

回答

0

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

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

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

感谢

+0

感谢您的答复,但我没有得到它,你能给我们解释更多,并添加一些代码? – Sam