首页 > 解决方案 > 使用 Swift 4 和 Firebase 从具有唯一 ID 的多个用户读取位置

问题描述

所以我已经为此苦苦挣扎了两天。我到处搜索,并没有真正找到可以帮助我的答案。也许我使用了错误的关键字。

这是问题所在。

我的 Firebase 实时数据库中有这些数据

-users
 VZUFNaLJ6YN5aqIDaFGmxWKGYNc2
  -location
     -latitude: 123
     -longitude: 123
 RXUFNaLJ6OI7G57DaFGmxWKHG76T
  -location
     -latitude: 321
     -longitude: 321

我希望得到的输出是这个


纬度:123

经度:123

纬度:321

经度:321


我真的没有可以在这里发布的工作代码,我希望有人可以帮助我了解需要做什么。谢谢你。

到目前为止我所拥有的是这个

// Read location from all user
        func globalCoor(){
        ref.child("location").observeSingleEvent(of: .value)
           { (snapshot) in
             let locationData = snapshot.value as? [String: Any]
            print(locationData)
            }
        }

标签: iosswiftfirebasefirebase-realtime-database

解决方案


试试这个,不用 Xcode 看看能不能用。请记住,如果您将其加载到 tableView/collectionView 中,则必须调用reloadData().

import UIKit
import FirebaseDatabase
import FirebaseAuth

class Example: UIViewController, UITableViewDelegate, UITableViewDataSource {

    //Vars
    var ref: DatabaseReference!
    var locations = [Locations]()


    override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference()

        retrieveData()
    }

    func retrieveData() {

        ref.child("users").observe(.value, with: { snapshot in
            for rest in snapshot.children.allObjects as! [DataSnapshot] {
                for child in rest.children {
                    let snap = child as! DataSnapshot
                    let dict = snap.value as? NSDictionary
                    let latitude = dict!["latitude"] as! String
                    let longitude = dict!["longitude"] as! String

                    let newElement = Locations(withArgs: latitude, longitude: longitude)
                    self.locations.append(newElement)
                }
            }
        })
    }
}


class Locations  {
    var longitude: String
    var latitude: String

    init(withArgs longitude: String, latitude: String) {
        self.longitude = longitude
        self.latitude = latitude
    }
}

推荐阅读