我有什么: 一個業務類別結構
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 結構如下所示:

我有一個功能可以獲取存盤在 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())")
}
}
}
}
uj5u.com熱心網友回復:
從 Firestore 獲取資料包含在入門指南讀取資料中
簡而言之,有兩種選擇(或更多);從檔案中獲取每個謹慎的欄位
for doc in querySnapshot!.documents {
let name = doc.get("name") as? String ?? "No Name"
}
或使用可編碼將資料作為整個物件讀取的首選方式
for doc in querySnapshot!.documents {
let cat = try doc.data(as: BusinessCategory.self)
}
這里有一個使用 Firestore 和可編碼物件的很棒的指南
在 Swift 中映射 Firestore 資料
這是一本很好的讀物,可以為您節省大量時間(和代碼行!)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465802.html
