繁体   English   中英

swift和firebase一直循环

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM