将数组从Firebase转换为String并在UITableView中显示每个数组

时间:2017-05-10 19:45:11

标签: ios swift uitableview firebase firebase-realtime-database

我正在尝试将Firebase中的数组显示为UITableView。这就是我所拥有的:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FriendCell", for: indexPath) as UITableViewCell

    let otherVC = FriendCell()
    otherVC.usernameText?.text = friends[indexPath.row]
    print(friends[indexPath.row])

    return cell    
}

当我print(friends[indexPath.row])时,它会正确显示该孩子中的所有用户。我试图让每个用户进入他们自己的UITableViewCell。我尝试引用单元格控制器然后获取与故事板链接的usernameText,但它不起作用。

1 个答案:

答案 0 :(得分:2)

这是一种糟糕的做法。使用类似下面的内容。

TableViewController.swift

import UIKit
import FirebaseDatabase
import FirebaseAuth

class TableViewController: UITableViewController {

var dbRef:FIRDatabaseReference!
var users = [User]()

override func viewDidLoad() {
    super.viewDidLoad()

    dbRef = FIRDatabase.database().reference().child("users")
    startObservingDB()
}

func startObservingDB () {
    dbRef.observe(.value, with: { (snapshot:FIRDataSnapshot) in
        var newUser = [User]()

        for user in snapshot.children {
            let userObject = User(snapshot: user as! FIRDataSnapshot)
            newUser.append(userObject)
        }

        self.user = newUser
        self.tableView.reloadData()

    }) { (error:Error) in
        print(error.localizedDescription)
    }

}

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(withIdentifier: "Cell", for: indexPath)

    // Configure the cell
    let userRow = user[indexPath.row]

    cell.usernameLabel?.text! = userRow.username

    return cell
}
}

您还需要数据模型User.swift

import Foundation
import FirebaseDatabase

struct User {

    var key:String!
    let itemRef:FIRDatabaseReference?
    var username:String!


    init (key:String = "",
          username:String) {

        self.key = key
        self.itemRef = nil
        self.usernam = username

    }

    init (snapshot:FIRDataSnapshot) {

        key = snapshot.key
        itemRef = snapshot.ref

        if let userUserName = snapshot.value as? NSDictionary, let _temporary = userUserName["username"] as? String {
            username = _temporary
        } else {
            username = ""
        }
    }

}