Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

how to load data from firebase swift 4

I'm trying to load data from firebase, but every time I add the append() array the build crashes and I get an error of Thread 1: signal SIGABRT. I've checked the storyboards and there are no unconnected outlets. when I remove the array the build doesn't crash but the data isn't displayed. I've been working on this problem for a few weeks and I would really like some help.

import Foundation
import UIKit
import Firebase

class HomeViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var posts = [Post]()

    override func viewDidLoad() {
        super.viewDidLoad()

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

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

        loadPosts()
    }

    func loadPosts() {

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

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

            for child in snapshot.children {

                if let childSnapshot = child as? DataSnapshot,
                   let dict = childSnapshot.value as? [String: Any],
                   let title = dict["title"] as? String  {

                    let posts = Post(title: title)
                    // this is what causes the problem
                    self.posts.append(posts)
                    ////////
                    print(snapshot.key)
                }

                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.textLabel?.text = posts[indexPath.row].title

        return cell
    }

}

this is the Post class/Structure

 import Foundation
    import UIKit

    class Post {

        var title: String


        init(title: String) { 
            self.title = title
        }


    }

Comments