[英]Duplicates child node when setting a value Firebase
在過去的幾天里,我一直在嘗試解決這個問題,但最終還是得到了相同的結果。 當用戶點擊添加好友時,會將好友的 id 作為節點添加到“好友”下(如預期的那樣); 但是,當我 go 嘗試更新或設置該 id 的值時,它會再次將 id 與該值一起添加,而不是僅將值添加到現有子項。 我如何制作它以便添加它而不添加整個其他孩子?
這是添加朋友的代碼:
func saveFriend(selectedFriend: FUser) {
if friendId.contains(selectedFriend.objectId as String) {
return
}
//get current friends
var currentFriends = FUser.currentUser()!.friends
currentFriends.append(selectedFriend.objectId)
let newDate = dateFormatter().string(from: Date())
let secondsDate: Int = Int(Date().timeIntervalSince1970)
updateUser(withValues: [kFRIEND : currentFriends, kUPDATEDAT : newDate, kSECONDSDATEUPDATED : secondsDate]) { (success) in
self.loadFriends()
NotificationCenter.default.post(name: .addedFriend, object: nil)
}
}
這是添加值的代碼(用 updateChildValues 注釋掉,我也嘗試過並得到相同的結果):
func increaseFriendshipValue(increase: Int) {
let friend = withUsers.first!.objectId
let friendValueRef = firebase.child(kUSER).child(FUser.currentId()).child(kFRIEND).child(friend)
// friendValueRef.updateChildValues([friend: +increase])
friendValueRef.setValue(increase)
}
編輯:這是我目前在我的朋友視圖中的內容,我從他們如何添加到數組中加載朋友(沒有值):
@objc func loadFriends() {
cleanup()
let friendIds = FUser.currentUser()!.friends
if friendIds.count > 0 {
for friendId in friendIds {
firebase.child(kUSER).queryOrdered(byChild: kOBJECTID).queryEqual(toValue: friendId).observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
let userDictionary = ((snapshot.value as! NSDictionary).allValues as Array).first
let fuser = FUser.init(_dictionary: userDictionary as! NSDictionary)
self.friends.append(fuser)
self.friendId.append(fuser.objectId)
self.friends.sort(by: {$0.username < $1.username})
}
self.tableView.reloadData()
}
}
} else {
ProgressHUD.showError("You currently have no friends saved. Please unlock some")
}
}
您正在以兩種不同的格式寫入數據。
首先在saveFriend
中,您以這種格式編寫:
"friends": {
"0": "uidOfTheUser",
"1": "uidOfAnotherUser"
}
然后在increaseFriendshipValue
中,您將其更新為:
"friends": {
"uidOfTheUser": 1,
"uidOfAnotherUser": 0
}
由於您似乎實際上希望為每個用戶保留一個計數,因此我將假設后者是正確的結構。 這意味着您也需要在saveFriend
中以該格式編寫用戶。
問題似乎出在:
var currentFriends = FUser.currentUser()!.friends
currentFriends.append(selectedFriend.objectId)
在這里,您將selectedFriend.objectId
添加到一個數組中,這意味着 Swift 生成一個新的數組元素:上面第一個 JSON 片段中的0
和1
。
您實際上想要做的是直接寫入數據庫,類似於您在increaseFriendshipValue
中所做的。 假設初始計數為0
,則類似於:
let friendsRef = firebase.child(kUSER).child(FUser.currentId()).child(kFRIEND)
let newFriendRef = child(selectedFriend.objectId)
newFriendRef.setValue(0)
需要注意的幾點:
saveFriend
似乎有覆蓋朋友現有值的重大風險。 您可能正在檢查用戶是否已經在代碼中的某處成為朋友,但在這里您也需要使用事務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.