【问题标题】:How to read the current users profile document in Firestore如何在 Firestore 中读取当前用户配置文件
【发布时间】:2021-06-01 06:16:56
【问题描述】:

我正在使用 Firestore 开发我的第一个 IOS 应用程序。我正在从“用户”集合中成功检索所有用户文档或具有文档名称的特定文档。但是,一旦我想查询 currentUsers 文档,我就遇到了麻烦。我需要用户配置文件 viewController 的数据。

我可以查询一个特定的文档并用这个代码打印它:

func loadUserData() {
    let userDocumentRef = Firestore.firestore().collection("users").document(
        "6tIzsXgbOMDIFpdgR18i")
    
    userDocumentRef.getDocument { (document, error) in
        if let document = document, document.exists {
            let userData = document.data().map(String.init(describing: )) ?? "nil"
            print("Document data: \(userData)")
        } else {
            print("document does not exist")
            
        }
    }
}

但是,一旦我尝试使用此代码获取 currentUsers 文档,就会收到“文档不存在”的错误:

func currentUserData() {
    let userID : String = (Auth.auth().currentUser?.uid)!
    let userRef = Firestore.firestore().collection("users").document(userID)
    userRef.getDocument { (document, error) in
        if let document = document, document.exists {
            let userData = document.data().map(String.init(describing: )) ?? "nil"
            print("Document data: \(userData)")
        } else {
            print("document does not exist")
            
        }
    }
}

这是 Firestore 中用户集合的屏幕截图。 Screenshot of Firestore users collection

我只是无法弄清楚我做错了什么,因此感谢任何帮助。

【问题讨论】:

    标签: ios swift google-cloud-firestore firebase-authentication


    【解决方案1】:

    映射文档时似乎存在问题。以下是如何将数据从 Firestore 映射到 Swift:

    struct UserProfile: Codable, Identifiable {
      @DocumentID var id: String?
      var userId: String
      var firstName: String
      // ... other attributes
    }
    
    func currentUserData() {
      // Note: this is unsafe, please use an auth state change listener instead
      // Also, please try to avoid using force unwrap - your app will crash if the attribute is nil
      let userID : String = (Auth.auth().currentUser?.uid)!
    
      let userRef = Firestore.firestore().collection("users").document(userID)
      userRef.getDocument { (document, error) in
        if let document = document, document.exists {
          let userData = document.data(as: UserProfile.self)
          print("Document data: \(userData)")
        } else {
          print("document does not exist")
        }
      }
    }
    

    以下是如何设置身份验证状态更改侦听器:https://firebase.google.com/docs/auth/ios/start#listen_for_authentication_state

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      相关资源
      最近更新 更多