Firebasedata not populating tableView



我正试图从Firebase读取数据,并将其写入tableView,但数据未填充tableView
当我在读取数据的闭包内打印数据时,它会正确打印,但在闭包外会打印空白值。它还在viewDidAppear内正确打印

import UIKit
import Firebase
class UserProfileTableViewController: UIViewController, UITabBarDelegate, UITableViewDataSource {

private var gotName: String = ""
private var gotAdress: String = ""
private var gotPhone: String = ""
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.separatorColor = UIColor.gray
//Get userinfo from database
let uid = Auth.auth().currentUser!.uid
let userInfoRef = Database.database().reference().child("userprofiles/(uid)")
userInfoRef.observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let name = value?["Name"] as? String ?? ""
let address = value?["Address"] as? String ?? ""
let phone = value?["Phone"] as? String ?? ""
self.gotName = name
self.gotAdress = address
self.gotPhone = phone
print("Print inside closure in viewDidLoad(self.gotName, self.gotAdress, self.gotPhone)") //This prints the correct data
// ...
}) { (error) in
print(error.localizedDescription)
}

let testRef = Database.database().reference().child("Test")
testRef.setValue(gotName) // Sets value to ""
print("Print inside outside in viewDidLoad(self.gotName, self.gotAdress, self.gotPhone)") //This prints blank values
}

override func viewDidAppear(_ animated: Bool) {
print("Print in viewDidAppear closure(self.gotName, self.gotAdress, self.gotPhone)") //This prints the correct data
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UserProfileCell") as! UserProfileCell
cell.userProfileLabel.text = gotName

return cell
}    

我在viewDidLoad中读取数据的闭包外的print语句是第一个在控制台中打印的语句,如果这很重要的话?

从Firebase或任何服务器服务获取数据都是以异步方式完成的。这就是为什么当您尝试在闭包之外打印变量时,它不会打印任何内容。尝试在闭包中调用tableView.reloadData(),它会显示您想要的数据。

最新更新