Firebase 和 swiftyJSON 解析

Edw*_*ter 2 json firebase swifty-json firebase-realtime-database

swiftyJSON 看起来非常适合解析 Firebase。最终想要的是两种可能性:

一个imageName代表一个单独的 ID,一个 s 列表imageName代表所有 ID。JSON 结构:

在此输入图像描述

可以正常检索 JSON 但不显示imageName值的代码:

ref.observe(FIRDataEventType.value) {
          (snapshot: FIRDataSnapshot!) in

            let json = JSON(snapshot.value)
            //  print("JSON:  \(json)")

            // PRINT IMAGENAME - NOT WORKING
            if let imageName = json[12345][0]["imageName"].string {
                print("imageName: \(imageName)")
            }

          // // PRINT IMAGENAME - NOT WORKING
          let theKeys = json.dictionary!.keys

          for key in theKeys {
            let imageName = json[0][0]["imageName"]
            print("imageName: \(imageName)")
          }
}
Run Code Online (Sandbox Code Playgroud)

我的最终结果是最终得到一个要在 CollectionView 中显示的 imageURL。看起来很接近,只是 swiftyJSON 格式不正确。谢谢。

Cyr*_*cia 5

首先,我认为你应该以“firebase 方式”解析你的数据,我想你可以调用它而不是使用 SwiftJSON。这就是我会用“firebase 方式”来做到这一点

    import FirebaseDatabase

    class ViewController: UIViewController {

        var ref: FIRDatabaseReference!

     override fun viewDidLoad() {
        super.viewDidLoad()

        ref = FIRDatabase.database().reference()


    }

    func retrieveData() {

        ref.child("12345").observe(.childAdded, with { (snapshot) in 

        let dict = snapshot.value as? [String: AnyObject]

        let imageNamed = dict!["imageName"] as? String

        print("\(imageNamed)")
    }

    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码对我来说效果很好

在 SwiftJSON 中,我不是 100% 确定这是否有效,但也许我们可以尝试

let json = JSON(snapshot.value) as? [String: AnyObject]

if let imageName = json!["12345"][0]["imageName"].string {

}

let theKeys = json.dictionary!.keys

for key in theKeys {
    let imageName = json[0][0]["imageName"]
    print("imageName: \(imageName)")
}
Run Code Online (Sandbox Code Playgroud)