[英]How to fetch the latest document in collection from Firebase Cloud Firestore using Swift
I'm successfully retrieving documents from a Firebase Firestore collection using the code below.我使用下面的代码成功地从 Firebase Firestore 集合中检索文档。 This is being used to create a list of food items for each user.这用于为每个用户创建食品列表。 The user manually adds the date when the food item is being added.用户手动添加添加食品的日期。 The date is being used to order the fetched data alongside the userId only retrieving the documents for that user.该日期被用于与 userId 一起对获取的数据进行排序,仅检索该用户的文档。
However, I'd like to be able to fetch the latest food item added for a separate view that displays only that latest item.但是,我希望能够获取添加的最新食品项目,以用于仅显示最新项目的单独视图。 This latest item will change as the user adds more items.这个最新的项目会随着用户添加更多项目而改变。
I'm struggling to find the best way to achieve this.我正在努力寻找实现这一目标的最佳方法。 Assigning foodItems[0] to a separate @Published variable 'latestFoodItem' straight after all foodItems are fetched doesn't seem to be working.在获取所有 foodItems 后立即将 foodItems[0] 分配给单独的 @Published 变量 'latestFoodItem' 似乎不起作用。
I might be thinking along the wrong lines as a beginner... foodItems could also be empty, which is causing me problems!作为初学者,我可能会沿着错误的思路思考...... foodItems 也可能是空的,这给我带来了问题!
func fetchFoodItemsData() {
let userId = Auth.auth().currentUser?.uid
db.collection("foodItems")
.whereField("userId", isEqualTo: userId)
.order(by: "date", descending: true)
.addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("No documents")
return
}
self.foodItems = documents.compactMap { queryDocumentSnapshot -> FoodItem? in
return try? queryDocumentSnapshot.data(as: FoodItem.self)
}
}
}
Here is the structure of my Cloud Firestore with some fake data:这是我的 Cloud Firestore 的结构,其中包含一些虚假数据:
Since you're already fetching all the items, I would recommend using a local transformation.由于您已经在获取所有项目,因此我建议您使用本地转换。
In your view model (or repository), use Combine to add a new subscriber to your foodItems
.在您的视图 model(或存储库)中,使用 Combine 将新订阅者添加到您的foodItems
。 Then, set up a pipeline that transforms the collection of food items by sorting them and then picking the first element.然后,设置一个管道,通过对食物进行排序然后选择第一个元素来转换食物的集合。 Finally, assign this value to a new published property.最后,将此值分配给新的已发布属性。
Here is some sample code I adapted from one of my own apps:这是我从自己的应用程序之一改编的一些示例代码:
public class FoodItemsRepository: ObservableObject {
// MARK: - Publishers
@Published public var foodItems = [FoodItem]()
@Published public var mostRecentFoodItem: FoodItem?
init() {
// ... other setup
$foodItems.map { items in
items
.sorted { $0.dateAdded > $1.dateAdded }
.first
}
.assign(to: \.mostRecentFoodItem, on: self)
.store(in: &cancellables)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.