0
votes

I want to fetch all user's first name on my Firebase database to table view cells. When I excute my code, it does not work. Firebase has user tuple. Inside of this tuple, I am storing all user's id. Inside of these id's, I am storing personalInfo tuple. Firstname is inside of this personalInfo. You can see my Firebase snapshot on below picture. Where is my problem on code ? Can anyone help me ? http://prntscr.com/huvdr9

//chatInfo.swift
class ChatInfo: UITableViewController {

    let cellId = "cellId"
    var users = [User] ()

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Geri", style: .plain, target:self, action: #selector(handleCancel))
        tableView.register(UserCell.self, forCellReuseIdentifier: cellId)
        fetchUser()
    }
    func handleCancel() {

        dismiss(animated: true, completion: nil)

    }
    func fetchUser() {

        Database.database().reference().child("user").observe(.childAdded, with: {(snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {

                let user = User()

                user.userId = dictionary["firstname"] as! String
                print(user.firstname)
                self.users.append(user)

                DispatchQueue.main.async(execute: {
                    self.tableView.reloadData()
                })
            }

        } , withCancel: nil)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return users.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        let user = users[indexPath.row]
        cell.detailTextLabel?.text = user.firstname
        cell.imageView?.image = UIImage(named: "mail")
        return cell
    }
    class UserCell: UITableViewCell {

        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
        }
        required init?(coder aDecoder: NSCoder) {
            fatalError("not implemented")
        }
    }

}
//user.swift
class User: NSObject {

    var userId : String?
    var latitude : Double?
    var longitude : Double?
    var firstname : String?
    var email : String? 
}
1

1 Answers

0
votes

You need to add a child for the user on line:

Database.database().reference().child("user").observe(.childAdded, with: {(snapshot) in

change it to this:

Database.database().reference().child("user").child("personalInfo").observe(.childAdded, with: {(snapshot) in