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

时间:2021-08-01 14:51:47

标签: swift firebase firebase-realtime-database

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

enter image description here

print(snapshot.value as?NSArray)

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

enter image description here

数据库图像:

enter image description here

enter image description here

型号:

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

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。

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