我的应用程序中有一个搜索功能,该功能可以运行,并从数据库返回值,并在屏幕上填充textviews。我要实现的是,如果更新了textview的值,则可以按保存按钮,并且在相同的数据库ID下更新从搜索返回的值。
这是我要实现的更新方法:
func updateRecord(){
guard let pub: String = searchText.text?.lowercased() else { return }
let databaseRef = Database.database().reference().child("Drinks")
let query = databaseRef.queryOrdered(byChild: "pub").queryStarting(atValue: pub).queryEnding(atValue: "\(String(describing: pub))\\uf8ff")
query.observeSingleEvent(of: .value) { (snapshot) in
guard snapshot.exists() != false else {
print("Error, doesn't exist")
return
}
DispatchQueue.main.async {
let signature = "E"
//adding drink data
let drink = [
"pub": self.pubName.text!.lowercased() as String,
"location": self.pubLocation.text!.lowercased() as String,
"price": self.price.text!.lowercased() as String,
"rating": self.rating.text!.lowercased() as String,
"comment": self.comment.text!.lowercased() as String,
"signature": signature
]
databaseRef.child(--How do I access this token, for the drink in the picture I need to get "Lzsx_Vv5x5WVFsig-Zl"--).setValue(drink)
return
}
}
}
基本上,在我的数据库中,我需要能够访问存储数据的自动生成的ID。我知道方法'updateChildValues'可以工作,也可以在再次存储信息时再次使用“ setValue”,但是如何访问存储数据的ID?
谢谢,E
答案 0 :(得分:1)
由于我一年没有使用Firebase,因此我不确定100%。但是,请尝试以下操作。
query.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.childrenCount > 0 {
for drink in snapshot.children.allObjects as! [DataSnapshot] {
let id = drink.key; print(id)
}
}
}