Firebase Data Retrieval - Edit Annotation

六眼飞鱼酱① 提交于 2019-12-10 11:36:24

问题


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

  1. Consider making coordinate, name, subtitle into var instead of let.
  2. Consider creating a Skatepark object first out of the data before sending it to the database. This constructor should do the trick

    init(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
    }
    
  3. I'd create a dictionary variable inside Skatepark 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!