2017-04-20 68 views
0

我试图将值添加到Firebase节点,并且当前的代码覆盖了已有的值。将值添加到Firebase节点而不是覆盖已有的值

我有我的数据库设置是这样的(我想增加一个UID为“参与者”):

"rooms" : { 
    "-Ki6fAHv6LS5pyx34nUr" : { 
     "messages" : { 
     "-Ki70oJOAsto1uIxJsLY" : { 
      "senderId" : "tzfHgGKWLEPzPU9GvkO4XE1QKy53", 
      "senderName" : "Timothy", 
      "text" : "Test" 
     } 
     }, 
     "participants" : { 
     "tzfHgGKWLEPzPU9GvkO4XE1QKy53" : true 
     }, 
     "roomName" : "Room One" 
    } 

这是我的代码,运行时另一用户的用户搜索,然后水龙头结果:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 

    // Add selected user's UID to current room's participants 
    let currentRoomParticipantsRef: FIRDatabaseReference = FIRDatabase.database().reference().child("rooms").child(currentRoomID).child("participants") 

    let newParticipantItem = [self.returnedUsersUID : true] 
    currentRoomParticipantsRef.setValue(newParticipantItem) 

    let alertController = UIAlertController(title: "Added!", message: "Your friend has been added to the room", preferredStyle: UIAlertControllerStyle.actionSheet) 

    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: {(alert :UIAlertAction!) in 
    }) 
    alertController.addAction(okAction) 

    self.present(alertController, animated: true, completion: nil) 
} 

这样做将覆盖UID [S]在“参与者”新价值已经上市。我如何将新的UID添加到列表中,而不是覆盖?

回答

2

而不是setValue(它确实用您的新词典替换整个节点),请尝试使用updateChildValues,它将更新值(或创建新值)而不覆盖已存在的键。

+0

完美!这就是我需要的。我可以在6分钟内接受答案。再次感谢! – KingTim

相关问题