![](/img/trans.png)
[英]CollectionView not reloading after retrieving data from Firestore
[英]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 与可编码对象一起使用
这是一本非常好的读物,将为您节省大量时间(和代码行!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.