I wrote this code to retrieve the current user name, it gets the name right but it keep looping, what can I do to solve it?
as you can see I put a print statement and its all loop. I hope my problem description is clear and get a solution.
func getChildName1 ()->String
{
let db = Firestore.firestore()
var childName : String = "nil"
db.collection("Child").getDocuments { snapshot, error in
if error == nil {
if let snapshot = snapshot {
print("in childName snapshot") //this keeps printing
DispatchQueue.main.async {
print("in childName DispatchQueue.main.async") //this keeps printing
self.childList = snapshot.documents.map { d in
Child(
id: d.documentID,
email:d["Email"]as? String ?? "",
name: d["name"]as? String ?? ""
)
}
}
}
}
else {
// Handle the error
}
}
for item in childList
{
if item.id == String(Auth.auth().currentUser!.uid)
{
childName = item.name
print(childName) //this keeps printing
}
}
return childName
} // end getChildName
Firstly, your task is a bit confusing because the function is designed to get a single string ( name
) but you fetch an entire collection of documents which suggests there may be multiple names to deal with, so I've modified the function to be more idiomatic. Secondly, you cannot return something useful from an asynchronous function without making it an async
function, which has limited support as of right now. Therefore, consider using a completion handler.
func getChildNames(completion: @escaping (_ name: String) -> Void) {
Firestore.firestore().collection("Child").getDocuments { (snapshot, error) in
guard let snapshot = snapshot else {
if let error = error {
print(error)
}
}
for doc in snapshot.documents {
if let email = doc.get("Email") as? String,
let name = doc.get("name") as? String {
let child = Child(id: doc.documentID,
email: email,
name: name)
self.childList.append(child)
completion(name)
}
}
}
}
getChildNames { (name) in
print(name)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.