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
版权声明:本文标题:swift - Codable error when trying to access Firestore - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744303011a2599673.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论