Swift 3和Firebase - 我已經成功設法在tableview單元格中獲取用戶的用戶名和電子郵件地址。但是,當用戶在單獨的視圖控制器上更改他的用戶名時,tableview不會更新 - 舊的用戶名仍顯示。請看看下面的代碼:Swift 3和Firebase - Tableview不更新
databaseRef.child("users").queryOrdered(byChild: "username").observe(.childAdded, with: { (snapshot) in
let key = snapshot.key
let snapshot = snapshot.value as? NSDictionary
snapshot?.setValue(key, forKey: "uid")
if(key == self.loggedInUser?.uid)
{
// don't add signed in user to array
}
else
{
var theUser = User()
theUser.key = key
theUser.fullname = snapshot?.value(forKey: "fullname") as? String
theUser.biography = snapshot?.value(forKey: "biography") as? String
theUser.location = snapshot?.value(forKey: "location") as? String
theUser.photoURL = snapshot?.value(forKey: "photourl") as? String
theUser.username = snapshot?.value(forKey: "username") as? String
self.arrayOfUsers.append(theUser)
//insert the rows
self.SearchUsersTableViewController.insertRows(at: [IndexPath(row:self.arrayOfUsers.count-1,section:0)], with: UITableViewRowAnimation.automatic)
self.tableView.reloadData()
}
})
我曾嘗試將tableview.reloadData()放在多個地方沒有成功。我也嘗試過使用:
DispatchQueue.main.async {
self.tableView.reloadData()
}
沒有成功。當他改變他的用戶名時,我想出了一個想法來再次追加用戶。但是,我不知道如何刪除舊的。我認爲最好的解決方案是添加觀察類型childChanged。問題是我找不到在用戶數組中更改其用戶名的用戶的索引。
如果有人幫我解決問題,我將不勝感激。
編輯:
我有一個struct用戶:
struct User {
var username: String?
var photoURL: String?
var biography: String?
var fullname: String?
var location: String?
var key: String?
}
對於.childChanged我已經使用該Priyamal建議的代碼:
databaseRef.observe(.childChanged, with: { snapshot in
let ID = snapshot.key //this is the firebaseKey
if let index = self.arrayOfUsers.index(where: {$0.key == ID}) {
let changedPost = self.arrayOfUsers[index]
//update the values
self.tableView.reloadData()
print("Change!")
}
})
然而,當我更改用戶名,我從來沒有去過「改變!」輸出在我的控制檯;因此,tableview不會改變。
然後數組根本沒有填充。它只能通過使用.childAdded(甚至沒有價值) –
現在試一試。這應該工作 – Priyamal
我得到一個錯誤:類型'NSDictionary?'的值?在這一行上沒有成員'keyID':if let index = self.usersArray.indexOf({$ 0.keyID == ID}) –