2017-04-20 30 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

相關問題