Firebase 和 swiftyJSON 解析

Firebase and swiftyJSON parsing

swiftyJSON 看起来很适合解析 Firebase。最后想得到的是 2 种可能性:

一个 imageName 代表一个单独的 ID,一个 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)")
          }
}

我的最终结果是在 CollectionView 中显示一个 imageURL。看起来很接近,只是没有正确设置 swiftyJSON 格式。谢谢。

首先我认为你应该解析你的数据 'firebase way' 我想你可以调用它而不是使用 SwiftJSON。这就是我的做法 'firebase way'

    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)")
    }

    }
}

上面的代码很适合我

在 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)")
}