我在_geoloc字段中有一个数组。每个索引都有纬度和经度坐标。因此,使用SWIFT我希望能够仅在索引0处获取lat和lng坐标,并将它们单独传递给字符串。我已经研究了几天而且我被卡住了。我试图创建一个新的字符串数组或AnyObject数组,我只是在索引0检索我需要的数据,并只将那2个lat / lng坐标传递给字符串值。我有几个失败的代码片段,我可以发布。
这是我试图做的事情的片段:(我对firebase真的很新,所以代码有点难看,因为我只想弄明白这一点)
Firestore.firestore().collection("users").document("626").getDocument { (document, error) in
if let document = document {
// let geo_array = document["_geoloc"]
var yourArray = [String]()
// let geo_location = [geo_array] as [AnyObject]
let array: [Any] = document["_geoloc"] as! [Any]
let tmpArray = array.map({ return String(describing: $0)})
let string = tmpArray.joined(separator: ",")
yourArray.append(string)
print(yourArray[0])
您只需要将Any中的对象转换为字典数组并获取第一个属性:
Firestore.firestore().collection("users").document("626").getDocument { document, error in
if let document = document {
var yourArray: [String] = []
if let location = (document["_geoloc"] as? [[String:Double]])?.first,
let latitude = location["lat"],
let longitude = location["lat"] {
let coordinate2d = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
yourArray.append("Latitude: \(location.latitude), Longitude: \(location.Longitude)")
}
}
}
也许首先声明这个:
var firstPositionValues = [AnyObject]()
然后像这样得到它:
let db = Firestore.firestore().collection("users").document("626")
db.getDocument { (document, error) in
if let document = document {
let geo_location = document["_geoloc"] as [AnyObject] // <- this is all of them in the document
var initialValues = geo_location[0] // <- here are your lat and lng at position 0
self.firstPositionValues = initialValues
}
希望我理解得好运。