【发布时间】:2017-05-17 14:41:35
【问题描述】:
我目前正在开发一个用户可以在他们的地图上保存注释的应用程序,这一切都很好!地图位置、名称和字幕都发送到数据库中,并放入地图中。
但是,我正在努力弄清楚如何从 [Firebase][1] 中提取这些数据,以便用户能够编辑以前的信息,然后对其进行更新。
【问题讨论】:
标签: swift firebase firebase-realtime-database annotations firebase-authentication
我目前正在开发一个用户可以在他们的地图上保存注释的应用程序,这一切都很好!地图位置、名称和字幕都发送到数据库中,并放入地图中。
但是,我正在努力弄清楚如何从 [Firebase][1] 中提取这些数据,以便用户能够编辑以前的信息,然后对其进行更新。
【问题讨论】:
标签: swift firebase firebase-realtime-database annotations firebase-authentication
要读取数据,您需要使用 firebase 参考中的 observe 属性。这将返回一个包含您的数据的snapshot。
由于您的Skatepark 类已经有一个快照构造函数,您所要做的就是将快照传递给它并创建您的对象。
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)
}
}
})
要更新您的价值观,您只需要this。
个人推荐
coordinate、name、subtitle 改为var 而不是let。考虑先从数据中创建一个Skatepark 对象,然后再将其发送到数据库。这个构造函数应该可以解决问题
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
}
我会在Skatepark 内创建一个dictionary 变量,该变量会根据对象创建一个字典。这样我的代码库中就不会出现["lat": locationManager.location?.coordinate.latitude, "lng": locationManager.location?.coordinate.longitude, "name": skateTitleText, "subtitle": skateStyleText, "type": (selected - 1), "editable": true]。
所以在你的班级里有这个
var dictionary: [String:Any]
{
return
[
"lat": coordinate.latitude,
"lng": coordinate.longitude,
"name": title,
"subtitle": subtitle,
"type": type,
"editable": editable
]
}
每次您想从对象中提取字典时,只需使用 object.dictionary
【讨论】:
let park = Skatepark(locationManager.location?.coordinate, skateTitleText, skateStyleText, (selected - 1), editable)。然后只需执行locationsRef.setValue(park.dictionary)