【问题标题】:Read Data from Firebase and Save Into an Array (Swift)从 Firebase 读取数据并保存到数组中 (Swift)
【发布时间】:2016-05-09 00:21:23
【问题描述】:
我一直在围绕一些看似非常简单的事情兜圈子,但我无法弄清楚。我只是想从 Firebase 读取数据并将其保存在数组中,以便我可以在我的应用程序中使用它。我知道如何读取数据,因为我可以在控制台中打印出以下数据:
var ref = Firebase(url: "<MYFIREBASEURL>")
ref.observeEventType(.ChildAdded, withBlock: { snapshot in
print(snapshot.value.objectForKey("title"))
})
我尝试了其中一些方法来保存到数组,但我无法让它工作,因为它不能直接解决我更简单的问题。
Adding Firebase data into an array
How to save data from a Firebase query
感谢您的帮助!
【问题讨论】:
标签:
ios
arrays
swift
firebase
【解决方案1】:
这就是我使用 Firebase 检索值并附加到数组的方式。 REF_POSTS 是对我在 Firebase 中的帖子对象的基于 url 的引用。请记住,firebase 对象本质上是字典,您需要从中解析数据并将其分配给变量才能使用它们。
var posts = [Post]()// put this outside of viewDidLoad
//put the below in viewDidLoad
DataService.ds.REF_POSTS.observeEventType(.Value, withBlock: { snapshot in
print(snapshot.value)
self.posts = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(postKey: key, dictionary: postDict)
self.posts.append(post)
}
}
}
self.postTableView.reloadData()
})
【解决方案2】:
我睡了之后才知道。在这里发帖是为了让下一个人更容易弄清楚。
// Class variables
var ref = Firebase(url: "https://<MYFIREBASEURL>")
var titlesArray = [String]()
// Under viewDidLoad
// "events" is the root, and "title" is the key for the data I wanted to build an array with.
let titleRef = self.ref.childByAppendingPath("events")
titleRef.queryOrderedByChild("title").observeEventType(.ChildAdded, withBlock: { snapshot in
if let title = snapshot.value["title"] as? String {
self.titlesArray.append(title)
// Double-check that the correct data is being pulled by printing to the console.
print("\(self.titlesArray)")
// async download so need to reload the table that this data feeds into.
self.tableView.reloadData()
}
})