首页 > 解决方案 > 在表格视图中显示 Firebase 数据

问题描述

我正在尝试检索存储在 Firebase 数据库中的信息,但我的 tableview 未显示该信息。我尝试使用打印函数来查看是否正在检索数据,它表明是这种情况,但是当我运行模拟器时 tableview 显示为空白。

我正在使用 Xcode 11,并且由于某种原因,我看过的每个教程都无法正常工作。

这是我的代码:


import UIKit
import Firebase
import FirebaseDatabase
import SwiftKeychainWrapper
import FirebaseAuth

class FeedVC: UITableViewController {
    
    var currentUserImageUrl: String!
    var posts = [postStruct]()
    var selectedPost: Post!

    override func viewDidLoad() {
        super.viewDidLoad()
        getUsersData()
        getPosts()
        // Do any additional setup after loading the view.
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func getUsersData(){

        guard let userID = Auth.auth().currentUser?.uid else { return }
        Database.database().reference().child("users").child(userID).observeSingleEvent(of: .value) { (snapshot) in
            if let postDict = snapshot.value as? [String : AnyObject] {
                self.tableView.reloadData()
            }
        }
    }
    
    struct postStruct {
        let firstName : String!
        let lastName : String!
    }
    
    func getPosts() {
        let databaseRef = Database.database().reference()
        databaseRef.child("profiles").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: {
                    snapshot in
                    let firstName = (snapshot.value as? NSDictionary)!["profileForename"] as? String
                    let lastName = (snapshot.value as? NSDictionary
                        )!["profileSurname"] as? String
                    print(firstName)
                    self.posts.append(postStruct(firstName: firstName, lastName: lastName))
                    print(self.posts)
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                })
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell else { return UITableViewCell() }
        
        let nameLabel = cell.viewWithTag(1) as! UILabel
        nameLabel.text = posts[indexPath.row].firstName
        return cell
    }



}

任何帮助将非常感激!

标签: swiftxcodefirebasetableview

解决方案


更新:由于PostCell是在表视图中的情节提要中创建的,因此它已成功注册并出列。所以问题被缩小到标签为 1 的标签上。尝试@IBOutlet为标签创建一个并使用它来设置UILabel.

截屏

然后在cellForRowAt

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

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell else { return UITableViewCell() }
    cell.firstNameLabel.text = posts[indexPath.row].firstName
    return cell
}

上一篇:你好像忘记registerPostCell

override func viewDidLoad() {
    super.viewDidLoad()
    //...
    tableView.register(PostCell.self, forCellReuseIdentifier: "PostCell")
}

注意:如果您已经PostCell在 Xib 中创建,请使用 nib 注册表方法。

更新:如果您想使用 Nib 方法注册,请使用:

tableView.register(UINib(nibName: <#T##String#>, bundle: nil), forCellReuseIdentifier: "PostCell") // provide the xib file name at the placeholder

推荐阅读