Firebase 实时数据库搜索解码错误

我搜索了数据库,得到了正确的结果。当我使用 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”,这就是我无法解码的原因吗?

Firebase 实时数据库搜索解码错误

print(snapshot.value as?NSArray)

当我打印(snapshot.value as? NSArray) 数组的根索引时显示为空。我不能因为这个原因解码吗?

Firebase 实时数据库搜索解码错误

数据库图像:

Firebase 实时数据库搜索解码错误

Firebase 实时数据库搜索解码错误

型号:

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")
            }
        }
    }
pjl0079 回答:Firebase 实时数据库搜索解码错误

我解决了我的问题。

referance.child("allQuiz").queryOrdered(byChild: "title").queryEqual(toValue: "Ağustos Test 1").observeSingleEvent(of: .childAdded) { snapshot in
            let find = snapshot.exists()
            if find  {
                do {
                    let questions = try FirebaseDecoder().decode(Quiz.self,from: snapshot.value ?? "")
                    print(questions)
                } catch {
                    debugPrint(error)
                }
            } else {
                print("not found")
            }
        }

我改变了这个功能。

.observeSingleEvent(of: .childAdded) { }
本文链接:https://www.f2er.com/1653.html

大家都在问