我是使用Firebase的新手,我正在努力了解如何使用swift的ios查询来访问我的firebase数据库的某些点。
我的数据库看起来像这样:
我试图检索所有数据然后定位位置数据以将引脚放在mapview上。 我的应用内置了Firebase和FirebaseDatabase pod,没有任何问题,但我们真的不知道从哪里开始。 任何帮助将不胜感激
答案 0 :(得分:2)
我将做的是以下内容:
首先,我会为人员创建struct
,为每个model
条目保存Person
。
您创建一个新的Swift文件并输入以下内容:
struct People {
var name: String = ""
var age: String = ""
var latitude: String = ""
var longitude: String = ""
var nationality: String = ""
}
然后,在ViewController
课程中,您创建NSArray
People
并将实例化为空。
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)")
}