I have a Book model looking like this:
struct Book: Identifiable {
var id = UUID().uuidString
var text: String
var styleReference: DocumentReference
var style: BookStyle //not in the Firestore Document
}
with the style looking like this:
struct BookStyle: Identifiable {
var id = UUID().uuidString
var imageUrlString: String
var fontString: String
}
This is what my Firestore Book model looks like:
I can fetch the Books like this:
func fetchData() {
db.collection("books").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else { return }
self.books = documents.compactMap { queryDocumentSnapshot -> Book? in
return try? queryDocumentSnapshot.data(as: Book.self)
}
}
}
My problem now is: Where should I get the BookStyle Data? I have the reference to the document but I don't know where to fetch and assign it.
you could try something like this (totally untested), with var style: BookStyle?
and a loop over the books:
func fetchData() {
db.collection("books").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else { return }
self.books = documents.compactMap { queryDocumentSnapshot -> Book? in
return try? queryDocumentSnapshot.data(as: Book.self)
}
// -- here
for i in self.books.indices {
db.document(self.books[i].styleReference).getDocument { (snapshot, error) in
let bookStyle = snapshot.compactMap { queryDocumentSnapshot -> BookStyle? in
return try? queryDocumentSnapshot.data(as: BookStyle.self)
}
self.books[i].style = bookStyle
}
}
}
}
}
struct Book: Identifiable {
let id = UUID().uuidString
var text: String
var styleReference: DocumentReference
var style: BookStyle? // <-- here optional
}
struct BookStyle: Identifiable {
let id = UUID().uuidString
var imageUrlString: String
var fontString: String
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.