Leem.fin Leem.fin - 21 days ago 7
Swift Question

Access snapshot data get from firebase database

I am developing iOS project which uses Firebase database.

I have a observer to observe new data added to my Firebase database:

rootRef.observeEventType(.childAdded, withBlock: {(snap) in
// I try to access "positions" like this
if let mySnap = snap {
let positions = mySnap.childSnapshot(forPath: "positions").value as? Array
// But the positions is nil
})


The
snap
received is like this (It is
print(snap)
):

Optional( Snap (-KWoKFfKZOkFyoLI9at_) {
positions = {
0 = {
x = 80;
y = 212;
};
1 = {
x = 80;
y = "212.5";
};
10 = {
x = 83;
y = 229;
}
};
});


What is the right way to access "positions" data that get from firebase database?

Answer

As you have added response of mySnap.childSnapshot(forPath: "positions").value in comment it is type of Array of Dictionary so type cast it to [[String: Any]].

let positions = mySnap.childSnapshot(forPath: "positions").value as? [[String: Any]]