在Swift中使用Firebase,如何从集合中提取文档以显示在文本视图中?
登录应用程序后,在设置页面中,在Swift中使用Firebase,如何从集合中提取文档以显示在文本视图中?,swift,firebase,google-cloud-firestore,Swift,Firebase,Google Cloud Firestore,登录应用程序后,在设置页面中,SettingsViewController,我希望用户能够在文本视图中查看他们的信息。然而,无论采用何种方法读取数据,我总是会收到Swift编译器的警告: 从“[String]”转换为不相关类型“String”总是失败 这是我的代码: func textViewFill() { let db = Firestore.firestore() db.collection("users").getDocuments() { (querySnapsho
SettingsViewController
,我希望用户能够在文本视图中查看他们的信息。然而,无论采用何种方法读取数据,我总是会收到Swift编译器的警告:
从“[String]”转换为不相关类型“String”总是失败
这是我的代码:
func textViewFill() {
let db = Firestore.firestore()
db.collection("users").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
let firstName = ["firstName"] as? String ?? ""
let lastName = ["lastName"] as? String ?? ""
let email = ["email"] as? String ?? ""
self.firstNameTextView.text = firstName
self.lastNameTextView.text = lastName
self.emailTextView.text = email
}
}
}
}
当我试图将文档定义为字符串时,会出现警告:
let firstName = ["firstName"] as? String ?? ""
let lastName = ["lastName"] as? String ?? ""
let email = ["email"] as? String ?? ""
无法将其显示为文本吗?您试图在此处将
数组
转换为字符串
。以下是您需要的:
let firstName = document.get("firstName") as? String ?? ""
let lastName = document.get("lastName") as? String ?? ""
let email = document.get("email") as? String ?? ""
您可以使用if-let展开可选项,并且不将数组强制转换为字符串。。它总是失败的
func textViewFill() {
let db = Firestore.firestore()
db.collection("users").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
if let document = querySnapshot!.documents.first {
print("\(document.documentID) => \(document.data())")
if let firstName = document.get("firstName") as? String ,
let lastName = document.get("lastName") as? String,
let email = document.get("email") as? String {
self.firstNameTextView.text = firstName
self.lastNameTextView.text = lastName
self.emailTextView.text = email
}
}
}
}
}
另一方面,不要优雅地展开错误,而是强制展开数据,同时展开它们:
if let snapshot=snapshot{…}else{if let error=error{print(error)}}