ios - Firestore- 在 Tableview 中显示数据

标签 ios swift uitableview google-cloud-firestore

我正在尝试将我的 Firestore 数据显示到我的 Tableview 中,但我似乎无法让它显示出来。

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()

    }

起初我尝试了下面这段代码,没有错误,但没有加载到 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 - Append to tableView when view is loaded 读取)我尝试了下面的代码,但我收到错误“无法将类型 '(name: String, content: String, timeStamp: Date?)' 的值转换为预期的参数类型'Sourse'"所以我尝试从所有代码中删除日期,但我仍然无法让它工作。

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 本身。我还用 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
    }

最佳答案

您需要在解析您的快照 后重新加载您的tableView。强制打开您的 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()
        }
    }

关于ios - Firestore- 在 Tableview 中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50192761/

相关文章:

ios - 如何保护我的音乐应用程序下载的音乐文件?

ios - Alamofire 获取 pdf 作为 NSData

ios - 如何在 UITableView 部分之间添加分隔符?

uitableview - (iOS)为什么导航 Controller 中的第二个 'push' segue总是崩溃?

ios - 具有自己的 Nib 和 UITableViewCell 子类的 TableViewCell 设计

ios - UITableView:通过拖放将单元格移动到另一个位置

ios - Charles 代理 SSL 连接不会显示主机名,仅显示 ips

ios - Cydia 包 preinst/postinst 无法重新加载启动守护进程

iphone - 在 iPhone TableView 单元格的单元格右侧添加小箭头

ios - 如何在 swift 的辅助功能中使用点击手势?