My database is structured like this:
{
"username123" : {
"6642" : {
"latitude" : 37.861639,
"longitude" : -4.785556,
"name" : "CEPSA"
}
}
}
The idea is that every user will have a list of favorite gas stations, identified by their ID (6642 in the example). However, I can't figure out how to get the data. Any help please? Edit: I tried this but it obviously doesn't work since I get back the whole thing, I just can't figure out how to get the id, latitude, longitude and name.
ref.child(user).getData(completion: { error, snapshot in
guard error == nil else {
print(error!.localizedDescription)
return;
}
if let gasStationDict = snapshot.value as? [String:String] {
guard let id = snapshot.value, let name = gasStationDict["name"], let longitude = gasStationDict["longitude"], let latitude = gasStationDict["latitude"] else { return }
let gasStation = GasStation(name: name, longitude: longitude, latitude: latitude, favorita: true, id: id)
}
});
ref is initialized like this:
var ref: DatabaseReference! = Database.database().reference()
and user is:
guard var user = UserDefaults.standard.string(forKey: "User") else { return }
refanduservariables are initialized?snapshot.valueas[String: String]and it's actually[String: [String: String]]or[String: [String: Int]. I would personally abandon that practice and usechildSnapshotto access nested data - it's a lot easier to read. See my answer here and maybe here