Database fetch exists only in its own function

狂风中的少年 提交于 2020-01-06 06:18:38

问题


I am trying to fetch all the user names in my database but the nameArray only contains values while its inside that function, how can I fix this?

DataService.instance.getAllUserNamesPlease { (returnedNamesArray) in
            self.nameArray = returnedNamesArray
}

for userName in nameArray {
            if(userName.lowercased() == name!.lowercased()){

                self.userNameTaken = true
                self.progressView.progress = Float(progress / self.nameArray.count)
                progress += 1/self.nameArray.count
                break
                }
            }

nameArray is empty in this loop

func getAllUserNamesPlease(handler: @escaping (_ userNames: [String]) -> ()){

        REF_USERS.observeSingleEvent(of: .value) { (userNameSnapshot) in
            guard let userNameSnapshot = userNameSnapshot.children.allObjects as? [DataSnapshot] else {return}
            var namesArray = [String]()
            for names in userNameSnapshot {
                let name = names.childSnapshot(forPath: "userName").value as? String ?? "No Name"
                namesArray.append(name)
            }
            handler(namesArray)
        }
    }

回答1:


Any code that needs access to the results of an asynchronous call, should be inside that callback/completion handler. So your loop over nameArray, needs to be inside the {} braces:

DataService.instance.getAllUserNamesPlease { (returnedNamesArray) in
    self.nameArray = returnedNamesArray

    for userName in nameArray {
        if(userName.lowercased() == name!.lowercased()){

            self.userNameTaken = true
            self.progressView.progress = Float(progress / self.nameArray.count)
            progress += 1/self.nameArray.count
            break
            }
        }
    }
}


来源:https://stackoverflow.com/questions/56351339/database-fetch-exists-only-in-its-own-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!