2017-12-31 167 views
0

Ich hole alle Benutzer-IDs aus meiner Firebase-Datenbank. Wenn ich das Programm ausführe, kann ich den Snapshot aller Benutzer-IDs auf der Konsole über den Code in Zeile 26 sehen. Aber der Code schreibt nicht in Tabellenzellen. Ich habe das mit Tutorial gemacht. Alles ist gleich mit Video. Aber es funktioniert nicht für mich Wo ist das Problem?Swift 3 Firebase-Daten in TableView schreiben

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)) 
     fetchUser() 
    } 
    func handleCancel() { 

     dismiss(animated: true, completion: nil) 

    } 
    func fetchUser() { 

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

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

       let user = User() 

       user.userId = dictionary["userId"] as! String 
       print(user.userId) // IT PRINTS ALL USERS TO CONSOLE 
       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 numberOfSections(in tableView: UITableView) -> Int { 
     return users.count 
    } 


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId) 

     let user = users[indexPath.row] 
     cell.detailTextLabel?.text = user.userId 
     return cell 
    } 
} 

Antwort

0

Sie überschreiben die falsche Methode

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

und Design der Zelle Stil im Interface Builder und verwenden Sie diese Methode in cellForRowAt

let cell = tableView.dequeueReusableCell(withCellIdentifier: cellId, for: indexPath) 
0

Wie pro Ihre Anforderung tatsächliche Art und Weise zum Abrufen Aufzeichnungen der Tabelle Tabellenzelle ist dies:

override func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withCellIdentifier: cellId, for: indexPath) 
    let user = users[indexPath.row] 
    cell.detailTextLabel?.text = user.userId 
    return cell 
}