Firestore-在Tableview中显示数据 [英] Firestore- Showing data in Tableview

查看:69
本文介绍了Firestore-在Tableview中显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Firestore数据显示到Tableview中,但似乎无法显示它.

I am attempting to show my Firestore data into my Tableview but I can't seem to get it to show up.

protocol DocumentSerializeable {
    init?(dictionary:[String:Any])
}

struct Sourse {
    var name: String
    var content: String
    var timeStamp: Date

    var dictionary: [String: Any] {
        return [
            "name": name,
            "content": content,
            "timestamp": timeStamp
        ]
    }
}


extension Sourse : DocumentSerializeable {
    init?(dictionary: [String : Any]) {
        guard let name = dictionary["name"] as? String,
            let content = dictionary["content"] as? String,
            let timeStamp = dictionary["timeStamp"] as? Date else {return nil}

        self.init(name: name, content: content, timeStamp: timeStamp)

    }
}

class SourseListTableViewController: UITableViewController {

    var db: Firestore!

    var sourseArray = [Sourse]()

    private var document: [DocumentSnapshot] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.delegate = self
        self.tableView.dataSource = self

        //initalize Database
        db = Firestore.firestore()
        loadData()

    }

起初,我在下面尝试了此代码,没有错误,但是表视图中未加载任何内容.

At first I tried this code below, there were no errors but nothing loaded in the tableview.

func loadData() {
    db.collection("sourses").getDocuments() {
        snapshot, error in
        if let error = error {
            print("\(error.localizedDescription)")
        } else {
            self.sourseArray = snapshot!.documents.flatMap({Sourse(dictionary: $0.data())})
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }
}

经过一番研究(从读取后,Firestore-在查看时追加到tableView已加载),我在下面尝试了此代码,但收到错误无法将类型'((名称:字符串,内容:字符串,timeStamp:日期?)'的值转换为预期的参数类型'Sourse'",所以我尝试过删除所有代码中的日期,但仍然无法正常工作.

After some research (reading from Firestore - Append to tableView when view is loaded ) I tried this code below, but I get the error "Cannot convert value of type '(name: String, content: String, timeStamp: Date?)' to expected argument type 'Sourse'" So I tried it with the date removed from all the code and I still couldn't get it to work.

func loadData() {
        db.collection("sourses").getDocuments() {
            snapshot, error in
            if let error = error {
                print("\(error.localizedDescription)")
            } else {
                for document in snapshot!.documents {

                    let data = document.data()
                    let name = data["name"] as? String ?? ""
                    let content = data["content"] as? String ?? ""
                    let timeStamp = data["timeStamp"] as? Date 

                    let newSourse = (name:name, content:content, timeStamp: timeStamp)
                    self.sourseArray.append(newSourse)
                }
            }
        }
    }

这是我的numberOfRows/CellForRow以确保其不是tableview本身.我还在我的情节提要中仔细检查了单元格标识符".

Here is my numberOfRows/CellForRow to make sure its not the tableview itself. I've also double checked the "cell identifier" with my storyboard.

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return sourseArray.count
    }


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

        let sourse = sourseArray[indexPath.row]

        cell.textLabel?.text = "\(sourse.name)"
        cell.detailTextLabel?.text = "\(sourse.content)"

        return cell
    }

推荐答案

您需要在解析Snapshot之后重新加载tableView.强制解开Snapshot:

You need to reload your tableView after parsing your Snapshot. It is also not a good idea to force unwrap your Snapshot:

.getDocuments { (snapshot, error) in

    if let error = error {

        print(error.localizedDescription)

    } else {

        if let snapshot = snapshot {

            for document in snapshot.documents {

                let data = document.data()
                let name = data["name"] as? String ?? ""
                let content = data["content"] as? String ?? ""
                let timeStamp = data["timeStamp"] as? Date ?? Date()
                let newSourse = Sourse(name:name, content:content, timeStamp: timeStamp)
                self.sourseArray.append(newSourse)
            }
            self.tableView.reloadData()
        }
    }

这篇关于Firestore-在Tableview中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆