admin管理员组

文章数量:1402851

I have an app where I am trying to use FirebaseFirestore and SwiftData to store data.

This is why I am using a class and not a struct. I would like to use Codable so I can get back Book objects and perform CRUD on them and send them back.

I keep running into the same error when I try to access FireStore to retrieve the data/

Error fetching data: valueNotFound(Swift.KeyedDecodingContainer<Hopli_v0_5.Books.CodingKeys5>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot get keyed decoding container -- found null value instead.", underlyingError: nil))

Obviously there is something wrong with my CodingKeys but I simply cannot figure it out.

BookModel

import Foundation
import SwiftData
import FirebaseFirestore

@Model
class Books: Codable {
    enum CodingKeys5: CodingKey {
        case name, pages
    }
    
    var name: String
    var pages: Int
     
    init(
        name: String,
        pages: Int = 0
    ) {
        self.name = name
        self.pages = pages
    }
    
    // Make class Codable for Firebase
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys5.self)
        self.name = try container.decode(String.self, forKey: .name)
        self.pages = try container.decode(Int.self, forKey: .pages)
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys5.self)
        try container.encode(name, forKey: .name)
        try container.encode(pages, forKey: .pages)
 
    }
}

BookViewModel

@MainActor
final class BooksViewModel: ObservableObject {
    @Published var errorMessage: String = ""
    
    init() {}
    
    func getBookData() async throws -> Books {
        let db = Firestore.firestore()
        
        let book = try await db.collection("Books").document().getDocument(as: Books.self)
          
        return book
    }
}

ContentView

import FirebaseFirestore

struct tempView: View {
    
    @StateObject var viewModel = BooksViewModel()

//    var books = [Books]()
    var body: some View {
        VStack{
            Button {
                Task{
                    do {
                        var hops = try await viewModel.getBookData()
                        print(hops)
                    } catch {
                        print("Error fetching data: \(error)")
                    }
                }
            } label: {
                Text("Get hops")
                    .buttonStyle(.borderedProminent)
            }
        }

本文标签: swiftCodable error when trying to access FirestoreStack Overflow