当我进入视图控制器时,我想在数组中加载数据。当我打印该数组时,它是空的,但是如果我使用刷新并再次打印该数组,他将被加载。这是代码:>
var information = [String]()
override func viewDidLoad() {
super.viewDidLoad()
loadinformation()
print(information)
}
func loadinformation() {
let ref = Database.database().reference()
let uid = Auth.auth().currentUser?.uid
let prof = ref.child("users").child(uid!).child("interess")
prof.observeSingleEvent(of: .value,with: { (snapshot) in
if let dict = snapshot.value as? [String: Any] {
let name = dict["FullName"] as! String
self.information.append(name)
}
})
}
答案 0 :(得分:1)
此行
prof.observeSingleEvent(of: .value,with: { (snapshot) in
是异步的,这意味着它不是作为代码的串行流运行的,您需要在此处打印它
let name = dict["FullName"] as! String
self.information.append(name)
print(self.information)
//
或使用完成
func loadinformation(completion:@escaping(_ arr:[String]?) -> Void ) {
var arr = [String]()
let ref = Database.database().reference()
let uid = Auth.auth().currentUser?.uid
let prof = ref.child("users").child(uid!).child("interess")
prof.observeSingleEvent(of: .value,with: { (snapshot) in
if let dict = snapshot.value as? [String: Any] {
let name = dict["FullName"] as! String
arr.append(name)
completion(arr)
}
else {
completion(nil)
}
})
}
致电
loadinformation { (result) in
print(result)
if let content = result {
self.information = content
self.collectionView.reloadData()
}
}