[英]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.