[英]swift and firebase keep looping
我寫了這段代碼來檢索當前的用戶名,它得到了正確的名字但它一直在循環,我能做些什么來解決它?
如您所見,我放置了一個 print 語句及其 all 循環。 我希望我的問題描述清楚並得到解決方案。
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
首先,您的任務有點令人困惑,因為 function 旨在獲取單個字符串( name
),但您獲取了整個文檔集合,這表明可能有多個名稱需要處理,因此我將 function 修改為更多慣用的。 其次,如果不將異步 function 變為async
function,則無法從異步 function 返回有用的東西,目前支持有限。 因此,請考慮使用完成處理程序。
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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.