首页 > 解决方案 > 无法获取用户 Firebase Firestore

问题描述

无法从 firebase 获取用户列表。打印返回 [] 。代码如下。任何帮助都是极好的!

let COLLECTION_USERS = Firestore.firestore().collection("users")

 func fetchUsers() {
    COLLECTION_USERS.getDocuments { snapshot, _ in
        guard let documents = snapshot?.documents else {return}
        self.users = documents.compactMap({try? $0.data(as: User.self)})
        print(self.users)
        }

我希望我已注册的 7 个用户打印该数据。

标签: swiftfirebasegoogle-cloud-firestore

解决方案


如果documents.count显示您有 7 个文档,但self.users在运行映射后不包含任何元素,这表明您的 Firestore 文档无法映射到您的 Swift 结构。

请确保 Swift 结构中的数据类型与 Firestore 文档中使用的类型相匹配。

您还应该使用更具容错性的代码。在您的代码中,您明确地将error参数放在闭包上 - 您不想这样做。

以下代码片段(取自官方文档)显示了如何执行此操作。

let docRef = db.collection("cities").document("BJ")

docRef.getDocument { (document, error) in
    // Construct a Result type to encapsulate deserialization errors or
    // successful deserialization. Note that if there is no error thrown
    // the value may still be `nil`, indicating a successful deserialization
    // of a value that does not exist.
    //
    // There are thus three cases to handle, which Swift lets us describe
    // nicely with built-in Result types:
    //
    //      Result
    //        /\
    //   Error  Optional<City>
    //               /\
    //            Nil  City
    let result = Result {
      try document?.data(as: City.self)
    }
    switch result {
    case .success(let city):
        if let city = city {
            // A `City` value was successfully initialized from the DocumentSnapshot.
            print("City: \(city)")
        } else {
            // A nil value was successfully initialized from the DocumentSnapshot,
            // or the DocumentSnapshot was nil.
            print("Document does not exist")
        }
    case .failure(let error):
        // A `City` value could not be initialized from the DocumentSnapshot.
        print("Error decoding city: \(error)")
    }
}

推荐阅读