我试图在函数之外获取Array的值,但是快照块结束后newArray的值就为空。 即使关闭结束后,我也想访问Array的值。 将值从“准备连接”传递到下一个View Controller后,该值仍然为空。
var newArray = [Any]()
func getData(refe: String) -> [Any]{
let currUser = Auth.auth().currentUser?.uid
let ref = Database.database().reference(fromURL: "MyURL").child("users/\(currUser!)/Questions/")
ref.child("\(refe)").observeSingleEvent(of: .childAdded, with:{ snapshot in
let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? DataSnapshot, let value = rest.value{
self.newArray.append(value as! Any)
}
print(self.newArray)
//This gives [test,test1,test2]
})
return newArray
// Here the Array is empty.
}
实际结果:[]
预期结果:[test,test1,test2]
我也尝试过这个。
func getData(refe: String, completion: @escaping (([Any]) -> ())) {
var newArray = [Any]()
let currUser = Auth.auth().currentUser?.uid
let ref = Database.database().reference(fromURL: "MYURL").child("users/\(currUser!)/Questions/")
ref.child("\(refe)").observeSingleEvent(of: .childAdded, with: { snapshot in
let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? DataSnapshot, let value = rest.value{
newArray.append(value)
}
completion(newArray)
})
}
并在辅助函数中调用它
func getDataD() -> [Any]{
let ref = getReference()
var arr = [Any]()
self.getData(refe: ref) { (array) in
arr = array
// This gives [test,test1,test2]
}
return arr
// This gives []
}
在调用该函数以准备segue之后
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let detailViewController = segue.destination as? HostOptionTableViewController
else {
return
}
detailViewController.ref = getReference()
self.getData(refe: detailViewController.ref) { (array) in
detailViewController.data = array
}
}
}
detailViewController.data执行后的实际结果应为[test,test1,test2] 但它是[]
答案 0 :(得分:0)
在getData
内调用prepareForSegue
为时已晚,这应该在导航到第二个vc的动作内
self.getData(refe:yourRef) { array in
self.performSegue(withIdentifier:"segueName",sender:array)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let detailViewController = segue.destination as? HostOptionTableViewController
else {
return
}
detailViewController.ref = getReference()
detailViewController.data = sender as! [Model] // Model is type of array
}
请求是异步的,导航将在获取数据之前进行