Firebasedata未填充tableView

时间:2018-11-09 09:42:58

标签: swift firebase uitableview firebase-realtime-database

我正在尝试从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语句?

1 个答案:

答案 0 :(得分:1)

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