【问题标题】:Firestore get array data at index 0Firestore 在索引 0 处获取数组数据
【发布时间】:2019-07-30 22:35:00
【问题描述】:

下面我在firestore中有一些数据。

我在 _geoloc 字段中有一个数组。这些索引中的每一个都有纬度和经度坐标。因此,使用 SWIFT,我希望能够仅获取索引 0 处的 lat 和 lng 坐标,并将它们分别传递给字符串。我一直在研究几天,我被困住了。我试图创建一个新的字符串数组或 AnyObject 数组,但我只是在索引 0 处检索我需要的数据,并且只将这 2 个 lat/lng 坐标传递给字符串值。我可以发布几个失败的 sn-ps 代码。

这是我试图做的一个 sn-p:(我对 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])

【问题讨论】:

    标签: swift firebase google-cloud-firestore


    【解决方案1】:

    您只需要将对象从 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["lon"] {
                let coordinate2d = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) 
                yourArray.append("Latitude: \(location.latitude), Longitude: \(location.Longitude)")
            }
        }
    }
    

    【讨论】:

    • 哦,我明白了,我声明我的数组错误。这回答了我的问题,我会标记它,但作为后续,如果我想获得第二个、第三个甚至第十个索引,那么正确的语法是什么? [[String:Double]])?[2] 不正确。
    • 只需删除第一个属性,您将拥有一个字典数组。您可以根据需要映射它们。现在我在手机上,但一旦有机会我会编辑帖子。
    • 我想通了,我在错误的位置引用了索引。 if let location = (document["_geoloc"] as? [[String:Double]]), let latitude = location[1]["lat"] { 感谢 @leo-dabus 的帮助,显然我需要阅读 swift 书籍并更好地了解数组。
    【解决方案2】:

    也许先声明一下:

      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
    
            }
    

    希望我理解正确,祝你好运。

    【讨论】:

      猜你喜欢
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2021-08-15
      • 2015-06-04
      • 1970-01-01
      相关资源
      最近更新 更多