swift - 当节点值未知/自动生成 Swift 时更新 Firebase 中的子值
问题描述
我的应用程序中有一个搜索功能,它可以从数据库返回值并在我的屏幕上填充文本视图。我想要实现的是,如果更新了 textview 的值,我们可以按下保存按钮,并且从搜索返回的值在相同的 db 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?
谢谢, 乙
解决方案
我不能 100% 确定,因为我已经一年没有使用 Firebase。但请尝试以下。
query.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.childrenCount > 0 {
for drink in snapshot.children.allObjects as! [DataSnapshot] {
let id = drink.key; print(id)
}
}
}
推荐阅读
- javascript - 如何获取当前日期并将其加速 5 倍速度以相同的速度更改时间和日期
- android - 有没有办法访问在 ARCore 中已知 3D 坐标的点的 RGB 值?
- json - 导入/加载几个大 JSON 文件的方法
- python - 将字符串转换为列表 Python
- openstack - openstack 错误 CRITICAL keystone [-] 未处理错误:KeyError: 'connection'
- windows - 迭代目录中的文件 - 使用包含 % 的参数发出命令
- php - 在 url 中发布 Json 数组
- python-hypothesis - 如何在假设中设置数据帧的最小和最大长度?
- python - 在 PyQt5 中使用 cv2.imshow 和 drawpixmap 的颜色图是不同的
- xcode - Xcode 不会自动完成任何 Alamofire 方法