Home > Back-end >  Read data from firestore and display in collectionView
Read data from firestore and display in collectionView

Time:04-28

What I have: A business Category struct

struct BusinessCategory: Codable, Identifiable {
@DocumentID var id: String?
var name: String?
var image: String?

enum CodingKeys: String, CodingKey {
case id
case name
case image
} }

creating some categories:

var categories: [BusinessCategory] = [
    .init(id: "id1", name: "Doctor", image: "https://icon.url"),
    .init(id: "id2", name: "Restaurant", image: "https://icon.url"),
    .init(id: "id4", name: "Citizen Service", image: "https://icon.url"),
    .init(id: "id5", name: "Barber Shop", image: "https://icon.url"),
    .init(id: "id6", name: "Corona-Test", image: "https://icon.url")
]

displaying them:

switch collectionView{
    case CategoryCollectionView:
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CategoryCollectionViewCell.identifier, for: indexPath) as! CategoryCollectionViewCell
        cell.setup(category: categories[indexPath.row])
        return cell
    default: return UICollectionViewCell()
    }

What I need: How can I display ALL businessCategories I stored in a firestore database? My firestore structure looks like this:

enter image description here

I have a function to get all documents stored in firestore, but I do not know how to get the document data displayed. More precisely I need the "name" and the "url" extracted and displayed in the collectionView.

func getAllCategories(){
    database.collection("categories").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.data())")
            }
        }
    }
}

CodePudding user response:

Getting data from Firestore is covered in the Getting Started Guide Read Data

In a nutshell there are two options (or more); get each discreet field from the document

for doc in querySnapshot!.documents {
   let name = doc.get("name") as? String ?? "No Name"
}

or the preferred way of reading the data as an entire object using codable

for doc in querySnapshot!.documents {
   let cat = try doc.data(as: BusinessCategory.self)
}

There's a great guide using Firestore with codable objects here

Mapping Firestore Data in Swift

It's a very good read and will save you a ton of time (and lines of code!)

  • Related