Reputation: 41
What Im trying to do is retrieve the Firestore data for a specific user (the user's books) and put it on a collection view like this picture. Currently I can only print the doc data on the console and thats where Im stuck. If you can help this is my Firestore data and my code. I didn't insert the collection view code because the collection view cell only has an image view (the books image). Thanks in advance :)
func fetchUserBooks() {
guard let uid = Auth.auth().currentUser?.uid else { return }
Firestore.firestore().collection("books").document(uid).getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data()
print(dataDescription ?? "")
} else {
print("Document does not exist")
}
}
}
Upvotes: 0
Views: 187
Reputation: 358
You can use this pod: CodableFirebase to decode the document from Firestore. You need to create a struct/class that can hold the data coming from the db.
struct Book: Codable {
var description: String?
.....
}
Afterward, the method fetchUserBooks() could look like this:
Firestore.firestore().collection("books")....
guard let model = try? FirestoreDecoder().decode(Book.self, from: document.data()) else { return }
Keep in mind that you are working with async code, you need to use completion handlers.
Upvotes: 1