问题
I am currently working on an application where the users can save an annotation on their map and this all works great! The map location, name and subtitle are all sent to the database and the pin is put into the map.
However, I am struggling to figure out how to pull this data back down from [Firebase][1] so the users are able to edit the previous information and then update it.
回答1:
To read data, you want to use the observe attribute from your firebase reference. This returns a snapshot
consisting of your data.
Since your Skatepark
class already has a snapshot constructor, all you'd have to do is pass the snapshot to it and create your object.
reference.child("yourNode").observeSingleEvent(of: .value, with: { (snapshot) in
/* Two things can happen here. Snapshot can either consist of one element or multiple.
To handle this, you want to iterate through the snapshot, create your Skatepark
object and populate it into your global skatepark array.
*/
if snapshot.value is NSNull
{
print("Error Getting Snapshot")
}
else
{
for (child in snapshot.children)
{
let snap = child as! FIRDataSnapshot
let skateObject = Skatepark(child) // this calls the constructor which take snapshot as parameter
globalSkateParkArray.append(skateObject)
}
}
})
To update your values, this is all you need.
Personal Recommendations
- Consider making
coordinate
,name
,subtitle
intovar
instead oflet
. Consider creating a
Skatepark
object first out of the data before sending it to the database. This constructor should do the trickinit(coordinate: CLLocationCoordinate2D, name: String, subtitle: String, type: SkateboardType, editable: Bool) { self.coordinate = coordinate self.name = name self.subtitle = subtitle self.type = type self.editable = editable }
I'd create a
dictionary
variable insideSkatepark
that creates a dictionary from the object. This way I won't have["lat": locationManager.location?.coordinate.latitude, "lng": locationManager.location?.coordinate.longitude, "name": skateTitleText, "subtitle": skateStyleText, "type": (selected - 1), "editable": true]
floating all around my codebase.
So have this in your class
var dictionary: [String:Any]
{
return
[
"lat": coordinate.latitude,
"lng": coordinate.longitude,
"name": title,
"subtitle": subtitle,
"type": type,
"editable": editable
]
}
Every time you'd want a dictionary out of your object, simply use object.dictionary
来源:https://stackoverflow.com/questions/44028023/firebase-data-retrieval-edit-annotation