从Firebase读取数据到阵列

时间:2019-02-08 19:44:44

标签: arrays swift database firebase

从firebase读取快照非常简单,尽管将信息传输到数组更复杂。我有这个快照

Snap (01-08-2019) {
    Sleep = "6.25 hrs";
    "Time Uploaded" = "07:10 AM";
}
Snap (01-09-2019) {
    Sleep = "6.72 hrs";
    "Time Uploaded" = "07:19 AM";
}
Snap (01-10-2019) {
    Sleep = "6.55 hrs";
    "Time Uploaded" = "07:10 AM";
}

我将如何为日期创建一个数组,为睡眠创建一个数组,并为上传的时间创建一个数组。

2 个答案:

答案 0 :(得分:0)

我认为您应该重新考虑如何在Firebase中存储数据。看起来与此类似。

enter image description here

我还考虑为当天创建一个数据模型,

class Day {
    var date: String
    var sleep: String
    var timeUploaded: String

    init(date: String, sleep: String, timeUploaded: String) {
        self.date = date
        self.sleep = sleep
        self.timeUploaded = timeUploaded
    }
}

然后,您可以像这样获取快照。

var days = [Day]()

private func fetchDays() {
    print(days.count)

    let ref = Database.database().reference().child("days")
    ref.observeSingleEvent(of: .value) { (snapshot) in
        guard let days = snapshot.value as? [String: Any] else { return }

        for (_,value) in days.enumerated() {
            guard let dayDict = value.value as? [String: String] else { return }
            let date = dayDict["date"] ?? ""
            let sleep = dayDict["sleep"] ?? ""
            let timeUploaded = dayDict["time_uploaded"] ?? ""

            //If you really want 3 different arrays just add them here
            // dateArray.append(date) and so on for the other two arrays
            let day = Day(date: date, sleep: sleep, timeUploaded: timeUploaded)
            self.days.append(day)
        }

        print(self.days.count)
    }
}
}

希望这会有所帮助。无法评论询问您的数据的结构。

答案 1 :(得分:0)

我建议不要将数据保留在不同的数组中,最好将一个类中每个节点的数据存储起来,然后保留这些类的数组。

让我们从一个保留所有数据的类开始

class ChronoClass {
    var node_id = ""
    var sleep = ""
    var time_uploaded = ""

    init(withSnapshot: DataSnapshot) {
        let nodeId = withSnapshot.key
        let someSleep = withSnapshot.childSnapshot(forPath: "sleep").value as? String ?? ""
        let someTime = withSnapshot.childSnapshot(forPath: "time_uploaded").value as? String ?? ""

        self.node_id = nodeId
        self.sleep = someSleep
        self.time_uploaded = someTime
    }
}

然后是一个类数组,以保留所有类

var sleepArray = [ChronoClass]()

最后是要在每个节点中读取的代码,填充类并将类存储在数组中。

func readFirebaseDataAndPopulateArray() {
    let sleepNode = self.ref.child("sleep_node")
    sleepNode.observeSingleEvent(of: .value, with : { snapshot in

        for child in snapshot.children {
            let snap = child as! DataSnapshot
            let aChrono = ChronoClass(withSnapshot: snap)
            self.sleepArray.append(aChrono)
        }

        for x in self.sleepArray { //just prints out what's in the array
            print(x.node_id, x.sleep, x.time_uploaded)
        }
    })
 }

以及基于您的结构的输出

01-08-2019 6.25 hrs 07:10 AM
01-09-2019 6.72 hrs 07:19 AM
01-10-2019 6.55 hrs 07:10 AM

使用类的优点是您可以对对象进行排序,搜索,外推或执行多种其他功能,而不必使用三个单独的数组。