在表格视图中显示Firebase中的用户数据

时间:2019-12-04 02:40:03

标签: swift firebase uitableview firebase-realtime-database

我试图在以编程方式设置的表格视图上显示“帖子”。当我运行该应用程序时,未显示存储在我的数据库中“ posts”节点下的数据。我已经尝试了好一阵子了,这确实让我感到困惑。这是下面用于显示数据的ViewController的代码。

import Foundation
import UIKit
import Firebase

class HomeViewController:UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView:UITableView!

    var posts = [Post] ()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView.backgroundColor = UIColor.blue

        let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: "postCell")
        view.addSubview(tableView)

        var layoutGuide:UILayoutGuide

        layoutGuide = view.safeAreaLayoutGuide

        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        tableView.reloadData()

        observePosts()

    }

    func observePosts() {
        let postsRef = Database.database().reference().child("posts")

        postsRef.observe(.value, with: { snapshot in

            var tempPosts = [Post]()
            for child in snapshot.children {
                if let childSnapshot = child as? DataSnapshot,
                    let dict = childSnapshot.value as? [String:Any],
                    let author = dict["author"] as? [String:Any],
                    let uid = author["uid"] as? String,
                    let username = author["username"] as? String,
                    let photoURL = author["photoURL"] as? String,
                    let url = URL(string:photoURL),
                    let text = dict["text"] as? String,
                let timestamp = dict["timestamp"] as? Double {

                    let userProfile = UserProfile(uid: uid, fullname: username, photoURL: url)
                    let post = Post(id: childSnapshot.key, author: userProfile, text: text, timestamp: timestamp)
                    tempPosts.append(post)
                }
            }

            self.posts = tempPosts
            self.tableView.reloadData()
        })
    }

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
        cell.set(post: posts[indexPath.row])
        return cell
    }
}

我的firebase规则如下所示:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

在尝试从Firebase加载表视图中的数据之前,我创建了模拟数据,并将其放入var posts = [Post] ()的数组中,该数据代替了该数组中的“ Post”,并且显示得很好,所以我没有确定发生了什么事。

1 个答案:

答案 0 :(得分:-1)

您的UITableView不在主线程上。 将此代码添加到您的observePosts()

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