Home > Mobile >  How to display Firestore data into mobile app using Swift?
How to display Firestore data into mobile app using Swift?

Time:01-30

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:

CodePudding user response:

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()
  •  Tags:  
  • Related