【发布时间】:2021-10-07 05:09:29
【问题描述】:
我搜索数据库并得到正确的结果。当我使用 snapshot.value 打印到控制台时,我可以看到数据但不能对其进行解码。这是什么原因?我与 debugPrint 分享了结果。
调试打印:
Swift.DecodingError.valueNotFound(Swift.KeyedDecodingContainer<Ehliyet_Sinavim.Quiz.(unknown context at $1016c285c).CodingKeys>, Swift.DecodingError.Context(codingPath: [_FirebaseKey(stringValue: "Index 0", intValue: 0)], debugDescription: "Cannot get keyed decoding container -- found null value instead.", underlyingError: nil))
打印(快照.值)
上面看起来是“null”,这就是我无法解码的原因吗?
print(snapshot.value as?NSArray)
当我 print(snapshot.value as?NSArray) 数组的根索引显示为空。因为这个原因我不能解码吗?
数据库图片:
型号:
struct QuizContainer: Codable, Hashable {
var allQuiz: [Quiz]?
}
struct Quiz: Codable, Hashable {
var title: String?
var test: [Test]?
}
enum TestSectionType: String, Codable, Hashable {
case A = "A"
case B = "B"
case C = "C"
case D = "D"
}
struct Test: Codable, Hashable {
var id: Int?
var question: String?
var isQuestionImage: Bool?
var isSectionImage: Bool?
var imageURL: String?
var sections: [TestSectionType.RawValue : String]?
var correct: String?
}
搜索功能:
func serach() {
Database.database().reference().child("allQuiz").queryOrdered(byChild: "title").queryEqual(toValue: "Ağustos Test 2").observe(.value) { snapshot in
let find = snapshot.exists()
if find {
print(snapshot.value) //When I print this.. I shared the output of this above
do {
let questions = try FirebaseDecoder().decode([Quiz].self, from: snapshot.value ?? "")
print(questions)
} catch {
debugPrint(error)
}
} else {
print("not found")
}
}
}
【问题讨论】:
-
你应该解码 Quiz 还是 QuizContainer ?喜欢
let questions = try FirebaseDecoder().decode(QuizContainer.self, from: snapshot.value ?? "")而不是let questions = try FirebaseDecoder().decode([Quiz].self, from: snapshot.value ?? "") -
我试过了.. :( 错误:Swift.DecodingError.typeMismatch(Swift.Dictionary
, Swift.DecodingError.Context(codingPath: [], debugDescription: "不是字典”,基础错误:nil)) 数据丢失,无法读取。 -
啊,好吧,它会打印出
Test的数组,但我不完全理解snapshot.value是如何工作的,但是使用[Test].self进行解码应该可以吗? -
[Test].self 这应该可以工作,但此代码不起作用。这太奇怪了,我花了一整天的时间。我无法解决这个问题。它在我上面分享的控制台图片中显示
。这就是它无法解码的原因吗? -
在
Struct Quiz中应该包含[Test]或Test。你有一个有意义的测验数组,但我看到的是一个测试字典而不是一个测试数组。
标签: swift firebase firebase-realtime-database