Я пытаюсь прочитать данные из 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
, является первым, который будет напечатан в консоли, если это имеет значение?