问题
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 imageName
s 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