gpt4 book ai didi

json - Firebase 和 swiftyJSON 解析

转载 作者:行者123 更新时间:2023-12-02 04:05:10 25 4
gpt4 key购买 nike

swiftyJSON 看起来非常适合解析 Firebase。最终希望有两种可能性:

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

enter image description here

可以正常检索 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 方式”解析你的数据,我想你可以调用它而不是使用 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)")
}

}
}

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

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

关于json - Firebase 和 swiftyJSON 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com