我有一个这样的数据库:
用户可以收藏这些地方。我通过保存ID来保存收藏的地方。我想只使用ID从数据库中获取收藏的位置。我无法弄清楚如何做到这一点。请帮忙!
答案 0 :(得分:1)
看来你问的是如何通过它的身份来获得一个地方
(Swift 4,Firebase 4)
使用ID
从数据库中获取收藏的位置
这将读取一个地方,placeId1
let placeRef = self.ref.child("places").child("placeId1")
placeRef.observeSingleEvent(of: .value, with: { snapshot in
let placeDict = snapshot.value as! [String: Any]
let info = placeDict["info"] as! String
let moreInfo = placeDict["moreinfo"] as! String
print(info, moreinfo)
})
这将读取所有位置(一次)并迭代它们
let allPlaces = self.ref.child("places")
allPlaces.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
let placeDict = snap.value as! [String: Any]
let info = placeDict["info"] as! String
let moreInfo = placeDict["moreinfo"] as! String
print(info, moreInfo)
}
})
注意:self.ref = Database.database()。reference()
答案 1 :(得分:0)
您可以使用它来检查每个地点ID与您存储的收藏地点ID。
ref.child("places").observe(.childAdded, with: { (snapshot) in
var newItems = [FIRDataSnapshot]()
for item in snapshot.children {
if let value = (item as! FIRDataSnapshot).value as? String {
// might want to do another loop if you have an array of places to check
if snapshot.value as? String == "favorite_place_id" {
// this is what you want
}
}
}
})
答案 2 :(得分:0)
self.ref.child("places").observe(.value) { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let placeDict = snap.value as! [String: Any]
let info = placeDict["info"] as! String
let moreInfo = placeDict["moreinfo"] as! String
print(info, moreInfo)
}
}