Catch
Catch

Reputation: 153

Firebasedata not populating tableView

I'm trying to read data from Firebase, and write it in a tableView but the data is not populating the tableView
When I print the data inside the closure where I read the data, it prints correctly, but outside the closure it prints blank values. It also prints correctly inside 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

    }    

The print statement outside the closure where I read data in viewDidLoad is the first to be printed in the console if that matters?

Upvotes: 0

Views: 50

Answers (1)

DionizB
DionizB

Reputation: 1507

Getting data from Firebase or from any server service is done in asynchronous way. That's why when you try to print variables outside closures it doesn't print anything. Try calling tableView.reloadData() inside closure and it will show your desired data.

Upvotes: 1

Related Questions