如何使用 Swift 访问 Firebase 数据库中的一组键值?

How to access a certain group of key values in Firebase Database with Swift?

我是 Firebase 的新手,正在努力了解如何使用带有 swift 的 ios 查询到达我的 firebase 数据库的某些点。

我的数据库看起来像这样:

JSON DATABASE

我正在尝试检索所有数据,然后定位位置数据以将图钉放在地图视图上。 我的应用程序中内置了 Firebase 和 FirebaseDatabase pods,没问题,但我真的不知道从那里去哪里。 任何帮助将不胜感激

我会做的是:

首先我会为 People 创建一个 struct,为每个 Person 条目保存一个 model

您创建一个新的 Swift 文件并输入以下内容:

struct People {

    var name: String = ""
    var age: String = ""
    var latitude: String = ""
    var longitude: String = ""
    var nationality: String = ""
}

然后,在您的 ViewController class 中,您创建一个 PeopleNSArray 并实例化为空。

var peoples: [People] = []

然后你创建一个函数来下载你想要的数据。

func loadPeople() {

    // first you need to get into your desired .child, what is in your case People
    let usersRef = firebase.child("People")
    usersRef.observeEventType(.Value, withBlock: { snapshot in

        if snapshot.exists() {

            // since we're using an observer, to handle the case
            // that during runtime people might get appended to 
            // the firebase, we need to removeAll, so we don't
            // store people multiple times
            self.peoples.removeAll()

            // then we sort our array by Name
            let sorted = (snapshot.value!.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: "Name",ascending: false)])

            for element in sorted {

                let name = element.valueForKey("Name")! as? String
                let age = element.valueForKey("age")! as? String
                let location = element.valueForKey("location")! as? NSDictionary
                let nationality = element.valueForKey("nationality")! as? String

                // then we need to get our lat/long out of our location dict
                let latitude = location.valueForKey("latitude")! as? String
                let longitude = location.valueForKey("longitude")! as? String

                // then we create a model of People
                let p = People(name: name!, age: age!, latitude: latitude!, longitude: longitude!, nationality: nationality!)

                // then we append it to our Array
                self.tweets.append(t)                    
            }
        }
        // if we want to populate a table view, we reload it here
        // self.tableView.reloadData()
    })        
}

例如UITableView加载后,我们需要调用viewDidAppear中的函数。

override viewDidAppear() {
    loadPeople()
}

现在我们有了一组人并且能够填充 UITableView 或打印值:

for p in peoples {
   print("name = \(p.name)")
   print("longitude = \(p.longitude)")
   print("latitude = \(p.longitude)")
}