Firebase获取数据字典

时间:2019-02-19 15:48:28

标签: swift firebase firebase-realtime-database

我不知道如何在Swift 4 Firebase中获取数据。我需要在字典中获取数据字典。

这是我在Firebase中的数据:

This My Data in firebase Please click this link to show Image

我想在“情节”中获取数据。

1 个答案:

答案 0 :(得分:1)

我首先创建一个NSObject类。为了使检索更加容易。

class EpShow: NSObject {

private var Ep1:String!
private var Ep2:String!

init(Ep1:String, Ep2:String) {
    self.Ep1 = Ep1
    self.Ep2 = Ep2
}

public func getEp1() -> String{
    return Ep1
}

public func getEp2() -> String{
    return Ep2
}

public func setEp1(one:String){
    Ep1 = one
}

public func setEp2(two:String){
    Ep2 = two
}

convenience override init() {
    self.init(Ep1: " ", Ep2: " ")
}

要添加到Firebase

var ref:DatabaseRefernce!
var counter:Int = 1
ref = Database.database().reference().child("Featured")

    ref.childByAutoId().child("Episodes").setValue([
        "Ep1": String(counter),
        "Ep2": String(counter + 1)
    ])

    counter += 1

并获取嵌套子项中的数据

private var ep = [EpShow]()
ref.observe(DataEventType.value, with: {(snapshot) in
        for idAutoChild in snapshot.children.allObjects as! [DataSnapshot]{
            for episodesChild in idAutoChild.children.allObjects as! [DataSnapshot]{
                let e = episodesChild.value as! [String:AnyObject]
                let epOne = e["Ep1"] as! String
                let epTwo = e["Ep2"] as! String

                let show = EpShow(Ep1: epOne, Ep2: epTwo)
                print("Ep1: \(show.getEp1()) \n Ep2: \(show.getEp2())")
                 self.ep.append(show)

            }
        }
    })