【发布时间】:2020-02-13 22:06:21
【问题描述】:
过去几天我一直在尝试解决这个问题,但结果还是一样。当用户点击添加好友时,会将好友的 id 作为节点添加到“好友”下(如预期的那样);但是,当我尝试更新或设置该 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")
}
}
【问题讨论】:
标签: ios swift firebase firebase-realtime-database