我想在tableView中顯示當前用戶的朋友,但我無法讓它完美工作,當列表中的某個人更改他的名字時,單元格會重複。Firebase多個觀察者複製單元格
JSON:
{
"users" : {
"friends_requests" : {
"EeLIxkOEfhMUlsM8WGnHdgeT8xW2" : {
"friends" : {
"WWOdh96Yr3Qs4N3GWDVq3OlQFfB2" : true
}
},
"WWOdh96Yr3Qs4N3GWDVq3OlQFfB2" : {
"friends" : {
"EeLIxkOEfhMUlsM8WGnHdgeT8xW2" : true
}
}
},
"profile" : {
"EeLIxkOEfhMUlsM8WGnHdgeT8xW2" : {
"birthday" : "02/08/2017",
"displayname" : "user2",
"email" : "[email protected]",
"gender" : "M"
},
"WWOdh96Yr3Qs4N3GWDVq3OlQFfB2" : {
"birthday" : "02/08/2017",
"displayname" : "user1",
"email" : "[email protected]",
"gender" : "M"
}
}
}
}
下面的代碼:
var friendList = [Userr]()
func addFriendObserver(_ update: @escaping() -> Void) {
CURRENT_USER_FRIENDS_REF.observe(.value, with: { (snapshot) in
self.friendList.removeAll()
let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? FIRDataSnapshot {
self.ref.child("users").child("profile").child(rest.key).observe(.value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: Any] else {
return
}
let user = Userr()
user.displayname = dictionary["displayname"] as? String
self.friendList.append(user)
DispatchQueue.main.async {
self.tableview.reloadData()
}
}, withCancel: nil)
我試過很多方法,問這個問題很多次,但還是沒能得到它的工作並沒有答案。
請有人可以幫我解決這個問題。
編輯:新的觀察員,我使用:
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
}
}
我用Userr爲測試。但用戶是主要的swift文件。
查看'self.friendList.removeAll()'嘗試打印'friendList.count'後查看是否所有用戶都被刪除。此外,你應該包括用戶代碼類與您的代碼 – Stefan
@斯特凡謝謝,我已經測試,並清空列表。我編輯了我的問題。 – Sam