从Firebase读取数据并保存到数组(Swift) [英] Read Data from Firebase and Save Into an Array (Swift)

查看:173
本文介绍了从Firebase读取数据并保存到数组(Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在围绕着一些似乎很简单的事情,但我无法弄清楚。我只是想从Firebase读取数据并将其保存在数组中,以便可以在我的应用程序中使用它。我知道如何读取数据,如下所示,以便在控制台中输出:

  var ref = Firebase(url :< MYFIREBASEURL>)

ref.observeEventType(.ChildAdded,withBlock:{snapshot in

print(snapshot.value.objectForKey(title))

))

我尝试了一些保存到数组的方法,但我不能得到它的工作,因为它不直接解决我的简单问题。

将Firebase数据添加到数组中



感谢您的帮助!

解决方案

睡觉之后,我想出了它。在这里发帖,以便下一个人更容易找出。

  //类变量
var ref = Firebase (url:https://< MYFIREBASEURL>)
var titlesArray = [String]()

//在viewDidLoad

//events 是根,标题是我想要建立一个数组的数据的关键。
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)

//双击打印到正确的数据
print(\(self.titlesArray))

//异步下载,所以需要重新载入这个数据输入的表
self.tableView。 reloadData()
}
})


I've been going around in circles about something that seems really simple, but I can't figure out it out. I simply want to read data from Firebase and save it in array so I can use it in my app. I know how to read the data as the following works for me to print out in the console:

 var ref = Firebase(url: "<MYFIREBASEURL>")

 ref.observeEventType(.ChildAdded, withBlock: { snapshot in

        print(snapshot.value.objectForKey("title"))

    })

I tried some of these approaches to save to an array, but I can't get it to work as it doesn't directly address my simpler question.

Adding Firebase data into an array

How to save data from a Firebase query

Thanks for your help!

解决方案

I figured it out after sleeping on it. Posting here to make it easier for the next person to figure out.

 // 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()
        }
    })

这篇关于从Firebase读取数据并保存到数组(Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆