首页 > 解决方案 > Swift - Firebase 如何在没有父级的情况下仅获取子级值

问题描述

在数据库中,我有一个名为“城市”的子城市,每个城市都有多个区域包含协调

我遍历了“城市”下的每个孩子以找到最近的位置并使用以下方法获取城市名称ref.child("cities").observe()

for child in snapshot.children {

    let childSnap = child as! DataSnapshot

    if let dicionary = childSnap.value as? [String: AnyObject]{

        var latitude1 = dicionary["latitude"] as! Double
        var longitude1 = dicionary["longitude"] as! Double
        var altitude1 = dicionary["altitude"] as! Double

假设最近的城市是“城市 2”,并将其放在一个名为 selectedCity 的变量中。所以我重复并将其添加到ref.child("cities").child(selectedCity)

ref.child("cities").child("\(city2)").observe(.childAdded, with: { (snapshot) in

     if let dicionary = snapshot.value as? [String : AnyObject] {

         print(dicionary)

         var altitude = dicionary["altitude"] as! Double
         var latitude = dicionary["latitude"] as! Double
         var longitude = dicionary["longitude"] as! Double
         var theCity = dicionary["cityName"] as! String

         if theCity == city2 {
             locationArray.add(location.init(area: area, city: theCity, latitude: latitude, longitude: longitude, altitude: altitude))
         }

     }

 })

这是我遇到的问题,我让所有孩子在“城市 1”和“城市 2”中的“城市”下,但跳过其他城市,然后让孩子在“城市 2”下,这是重复数据

我怎样才能让它跳过父“城市”并转到子“城市 2”并获取一次数据

标签: iosswiftfirebasefirebase-realtime-database

解决方案


I solved it in a different way then what i was trying to do.

I placed all the data in a custom array - NSMutableArray() then lopped through that array and added an if statement (city == city2) if it is true then the row is placed in a new array


推荐阅读