有人可以帮助我从Firebase的收藏夹中检索“名字”数据。我想在用户个人资料上将用户名显示为名为“ nameLable”的UILable,但是我不确定如何?
如果有人可以帮助,我希望每个用户都能在个人资料页面上看到他们的名字!我正在使用Cloud Firestore。
答案 0 :(得分:3)
您可以使用下面的代码来获取文档列表中每个用户的名字。
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
}