Swift和ios 14中Firebase Firestore文档的访问字段



首先,我对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")
}
}

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

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

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")
}
}

最新更新