数据库获取仅存在于其自身功能中

时间:2019-05-28 23:42:11

标签: ios swift firebase firebase-realtime-database

我正在尝试获取数据库中的所有用户名,但是nameArray仅在函数内部包含值,我该如何解决呢?

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在此循环中为空

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 个答案:

答案 0 :(得分:1)

任何需要访问异步调用结果的代码都应该位于回调/完成处理程序的内部。因此,您在nameArray上的循环必须在{}大括号内:

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
            }
        }
    }
}