簡體   English   中英

從firestore中讀取數據並顯示在collectionView中

[英]Read data from firestore and display in collectionView

我有什么:業務類別結構

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

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

創建一些類別:

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")
]

顯示它們:

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()
    }

我需要什么:如何顯示存儲在 firestore 數據庫中的所有businessCategories? 我的 Firestore 結構如下所示:

在此處輸入圖像描述

我有一個 function 來獲取存儲在 firestore 中的所有文檔,但我不知道如何顯示文檔數據。 更准確地說,我需要提取並顯示在 collectionView 中的“名稱”和“url”。

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())")
            }
        }
    }
}

從 Firestore 獲取數據包含在入門指南中 閱讀數據

簡而言之,有兩種選擇(或更多); 從文檔中獲取每個謹慎的字段

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

或使用 codable 將數據作為整個 object 讀取的首選方式

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

這里有一個很好的指南,將 Firestore 與可編碼對象一起使用

映射 Swift 中的 Firestore 數據

這是一本非常好的讀物,將為您節省大量時間(和代碼行!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM