Reputation: 1
Im have a database like this:
The user will be able to favorite the places. I save the favorited places by saving the ids. I want to only get the favorited places from the database by using the IDs. I can´t figure out how to do this. Please help!
Upvotes: 0
Views: 3157
Reputation: 1
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)
}
}
Upvotes: 0
Reputation: 35648
It appears you are asking how to get a place by it's ID
(Swift 4, Firebase 4)
get the favorited places from the database by using the IDs
This will read a single place, 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)
})
this will read all the places (at once) and iterate over them
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)
}
})
note: self.ref = Database.database().reference()
Upvotes: 1
Reputation: 492
You can use this to check each place id with your stored favorite place ids.
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
}
}
}
})
Upvotes: 0