使用Swift 4和Firebase从具有唯一ID的多个用户读取位置

时间:2018-08-28 19:38:34

标签: ios swift firebase firebase-realtime-database

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

这是问题所在。

我的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)
            }
        }

1 个答案:

答案 0 :(得分:0)

尝试一下,没有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
    }
}