【发布时间】:2020-06-27 17:56:32
【问题描述】:
有人可以帮助我从我在 firebase 中的集合中检索“名字”数据吗?我想将用户配置文件上的用户名显示到一个名为“nameLable”的 UILable,但我不确定如何?
如果有人可以提供帮助,我希望每个用户都能在个人资料页面上看到他们的名字!我正在使用 Cloud Firestore。
【问题讨论】:
标签: swift firebase google-cloud-firestore uilabel
有人可以帮助我从我在 firebase 中的集合中检索“名字”数据吗?我想将用户配置文件上的用户名显示到一个名为“nameLable”的 UILable,但我不确定如何?
如果有人可以提供帮助,我希望每个用户都能在个人资料页面上看到他们的名字!我正在使用 Cloud Firestore。
【问题讨论】:
标签: swift firebase google-cloud-firestore uilabel
您可以使用以下代码获取文档列表中每个用户的名字。
func getName(Completion: @escaping((String) -> ())) {
let collectionRefernce:CollectionReference!
let db = Firestore.firestore()
collectionRefernce = db.collection("members")
collectionRefernce.getDocuments { (querySnapshot, error) in
if error != nil {
print("Error is \(error!.localizedDescription)")
} else {
guard let snapshot = querySnapshot else { return }
for document in snapshot.documents {
guard let myData = document.data() else { return }
let firstname = myData["firstName"] as? String ?? "No Name Found"
Completion(firstname)
}
}
}
}
这将检索每个用户的firstname。调用函数:
getName{ (name) in
label.text = name
}
如果您想检索当前登录用户的名字,请使用下面的代码
let id = Auth.auth().currentUser!.uid
func getName(Completion: @escaping((String) -> ())) {
let DocRefernce:DocumentReference!
let db = Firestore.firestore()
DocRefernce = db.collection("members").document(id)
DocRefernce.getDocument { (docSnapshot, error) in
if error != nil {
print(error!)
} else {
guard let snapshot = docSnapshot, snapshot.exists else { return }
guard let data = snapshot.data() else { return }
let firstname = data["firstName"] as? String ?? "No name"
Completion(firstname)
}
}
}
然后像这样在viewDidLoad中调用它
getName{ (name) in
label.text = name
}
【讨论】: