简体   繁体   English

如何使用 Swift 从 Firebase Cloud Firestore 获取集合中的最新文档

[英]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.

相关问题 如何使用swift更新firebase firestore中的文档? - How to update a document in firebase firestore using swift? 如何使用 swift 在 Firebase Cloud Firestore 中获取文档的 position? - How do I get the position of a document in Firebase Cloud Firestore using swift? 从 Firestore 集合中获取最后一个文档 - fetch the last document from Firestore collection 如何通过文档 ID - iOS 从 Firebase Firestore 获取数据? - How to fetch data from Firebase Firestore by document ID - iOS? Firebase Cloud Firestore - 从参考访问集合 - Firebase Cloud Firestore - Accessing a collection from a reference 如何从 Swift 中的 Cloud FireStore Firebase 访问特定字段 - How to access a specific field from Cloud FireStore Firebase in Swift 如何从 swift 的 Firebase Firestore 中删除当前用户的特定文档? - How to delete specific document for the current user from Firebase Firestore in swift? 如何使用 Xcode 中的 Swift 访问 Firebase 中的 Cloud Firestore 数据库中的数据? - How do I access the data from Cloud Firestore database in Firebase using Swift in Xcode? 如何在 Swift 中不硬编码用户集合文档 ID 的情况下将数据添加到 Firestore Cloud - How to add data to Firestore Cloud without hardcoding user collection document id in Swift Swift&Firebase-云Firestore可扩展吗? - Swift & Firebase - Cloud firestore scalable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM