【问题标题】:Access Fields of Firebase Firestore Document In Swift and ios 14?在 Swift 和 ios 14 中访问 Firebase Firestore 文档的字段?
【发布时间】:2021-05-09 23:23:03
【问题描述】:

首先,我对 firebase 很陌生,所以这可能是一个很容易回答的问题。我在 firebase 上使用 firestore 将用户名和全名保存在以用户电子邮件为名称的文档下以及标题为 users 的集合中。在 ios 14 中,没有 AppDelegate 页面,所以我一直在下面放置处理 firebase 的内容:

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions
                        launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool

我看到这个示例代码来获取一个文档:

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

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
        print("Document data: \(dataDescription)")
    } else {
        print("Document does not exist")
    }
}

但在此之后我不知道如何访问用户名和全名。甚至如何正确存储此文档?我在这里做什么?

【问题讨论】:

    标签: ios swift firebase google-cloud-firestore


    【解决方案1】:

    要从检索到的文档中获取字段值,您可以这样做:

    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
            print("Document data: \(dataDescription)")
            
            let data = document.data()
            let username = data!["username"]! as? String ?? ""
            let fieldName = data!["fieldName"]! as? String ?? ""
            print(username)
        } else {
            print("Document does not exist")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 2018-07-04
      • 1970-01-01
      • 2023-01-01
      相关资源
      最近更新 更多