Reputation: 23
This is how my JSON nested DB looks:
Its a pets
root that has multiple unique IDs. Then each ID represents a pet with some properties, some of them (like feedingList
and walkingList
) also contain more values inside that represent meals/walks and their time and completion Boolean.
I have written code in Swift to retrieve some of the values, but I have problem reaching those fList
and wList
.
func getPetInfo() {
let refMeals = reff.child("pets")
refMeals.observe(.value, with: { (snapshot) in
if let snapCast = snapshot.value as? [String:AnyObject]{
for snap in snapCast{
if self.currentUser.pets.contains(snap.key) {
if let x = snap.value["name"] as? String{
self.tempPet.name = x
print(x)
}
if let y = snap.value["type"] as? String{
//self.tempPet.type = y
print(y)
}
if let z = snap.value["age"] as? Int{
//self.tempPet.age = z
print(z)
}
print(snap.value["fList"])
if let w = snap.value["fList"] as? [String:AnyObject]{
for snippete in w {
if let a = snippete.value["time"] as? String{
//self.tempPet.feedingList.append(a)
print(a)
}
if let b = snippete.value["doneForToday"] as? Bool{
//self.isItDoneForToday.append(b)
print(b)
}
}
}
if let r = snap.value["wlist"] as? [String:AnyObject]{
for snippete in r {
if let c = snippete.value["time"] as? String{
//self.tempPet.feedingList.append(a)
print(c)
}
if let d = snippete.value["doneForToday"] as? Bool{
//self.isItDoneForToday.append(b)
print(d)
}
}
}
//self.petArray.append(self.tempPet)
}
}
}
}) { (error) in
print(error.localizedDescription)
}
}
It all prints out okay for name
, age
and type
, but when it comes to this line of code:
if let w = snap.value["fList"] as? [String:AnyObject]
...
It doesn't let it and nothing prints out. Can you tell me where I'm wrong? I'm clearly having trouble understanding values and arrays of this JSON tree. It's a mess when I'm trying to understand what to get
and convert to what. Thanks in advance.
This is what gets printed out:
blasted
cat
3
Optional(<__NSArrayM 0x60800024f000>(
{
doneForToday = 0;
time = "12:00";
}
)
)
Upvotes: 2
Views: 642
Reputation: 9955
Try this:-
if let r = snap.value["wlist"] as? [Int:AnyObject]{
for snippete in r {
if let c = snippete.value["time"] as? String{
//self.tempPet.feedingList.append(a)
print(c)
}
if let d = snippete.value["doneForToday"] as? Bool{
//self.isItDoneForToday.append(b)
print(d)
}
}
}
//self.petArray.append(self.tempPet)
}
Upvotes: 1