Reputation: 147
currently my data is as such
{
'listone':
{
'entrydate1':
{
'random key 1':
{
'name': 'Chris';
'date': '24 May 2016'
}
'random key 2':
{
'name': 'John';
'date': '25 May 2016'
}
}
'entrydate2':
{
'random key 1':
{
'name': 'Chris';
'date': '24 May 2016'
}
'random key 2':
{
'name': 'John';
'date': '25 May 2016'
}
}
}
}
The random key is generated by firebase childByAutoID()
The question is when I get my snapshot, how do I get the details of each random key? Basically I need to retrieve the data from listone
and I will populate my tableview
by sorting the earliest entrydate
. however after getting the snapshot I am lost as to how I can get the information out of the snapshot.
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference()
let uid = FIRAuth.auth()!.currentUser!.uid
let listOneRef = ref.child(uid + "/listone")
_ = listOneRef.observeEventType(.Value, withBlock: { (snapshot) in
for item in snapshot.children {
let child = item.children.allObjects
for snap in child {
//anyitems was initialized as [AnyObject] array
self.anyitems.append(snap)
}
}
self.tableView.reloadData()
})
I have no idea how to actually make use of the details. when I print anyitems
I do see some details i.e.
[Snap (-KJ-jqTNf3MTtY8YRH-3) {
Name = "Chris";
Date = "30 May 2016";
}, Snap (-KJ01QYoTedZkClsf13Y) {
Name = "John";
Date = "30 May 2016";
}]
Upvotes: 1
Views: 877
Reputation: 70118
I'm not on Xcode right now so I can't verify, but it should be something like:
for snapshot in anyitems {
print(snapshot.value.objectForKey("Name"))
}
And I think subscripting should also work:
for snapshot in anyitems {
print(snapshot.value["Name"])
}
If you need to tell the type to the compiler:
for snapshot in anyitems as! [FIRDataSnapshot] {
print(snapshot.value.objectForKey("Name"))
}
But it would be better, as you've noticed, to safely cast the array before accessing its content:
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
}
Upvotes: 2