0

I would like to display data from the Firestore database into my mobile app using the Swift TableView however I am stuck with the coding.

import UIKit
import Firebase
import FirebaseAuth
import FirebaseFirestore

class BookListViewController: UIViewController {
    
    var bookCollectionRef: CollectionReference!
    
    var books = [Books]()
    var id: String
    var bookAuthor: String
    var bookSummary: String
    var bookTitle: String
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        bookCollectionRef = Firestore.firestore().collection("bookData")
        bookCollectionRef.getDocuments { [weak self] (snapshot, error )   in
            if let err = error {
                debugPrint("Error fetching docs: \(err)")
            } else {
               guard let snap = snapshot else {return}
                for document in snap.documents {
                    let data = document.data()
                    _ = data[self?.bookAuthor ?? <#default value#>] as? String ?? "Anonymous"
                    _ = data[self?.bookSummary] as? String ?? ""
                    _ = data[self?.bookTitle] as? String ?? ""
                

The collection that I wanted to display is the bookData:

2
  • Hi Abeeget, Can you please share the complete else block as I wanted to know whether you had appended your books array or not with this data which you are fetching? Jan 30, 2022 at 3:56
  • @SaurabhPathak else { if let snapshot = snapshot { for document in snapshot.documents { let data = document.data() let author = data["bookAuthor"] as? String ?? "" let title = data["bookTitle"] as? String ?? "" let summary = data["bookSummary"] as? String ?? "" }
    – Abeeget
    Jan 30, 2022 at 4:08

1 Answer 1

0

I think you forget to append your books array with fetched data and don't forget to reload tableview.

Try this code:

else {                                  
    if let snapshot = snapshot {                                      
    for document in snapshot.documents {                                          
      let data = document.data()                     
      let author = data["bookAuthor"] as? String ?? ""                     
      let title = data["bookTitle"] as? String ?? ""                     
      let summary = data["bookSummary"] as? String ?? "" 
      let newBook = (bookAuthor:author,booktitle:title,bookSummary:summary)
      self.books.append(newBook)
}

self.tableview.reloadData()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.