Firebase and swiftyJSON parsing

隐身守侯 提交于 2019-12-11 01:36:51

问题


swiftyJSON looks great for parsing Firebase. What would like to end up with is 2 possibilities:

An imageName for one individual ID, and a list of imageNames for all IDs. JSON Struture:

Code that retrieves JSON fine, but does not display imageName values:

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

My end result is to end up with an imageURL to display in a CollectionView. It seems close, just not getting the swiftyJSON format correct. Thanks.


回答1:


First I think you should parse your data the 'firebase way' I guess you can call it instead of using SwiftJSON. This is how I would do it the '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)")
    }

    }
}

The code above works well for me

in SwiftJSON, I'm not 100% sure if this will work but maybe we could try

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


来源:https://stackoverflow.com/questions/39851347/firebase-and-swiftyjson-parsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!