0

I am new to Swift. I know how to get a single piece of data from Firebase, but when I try to get a list of data into an array, I get no error or no data. Please help me. I have been struggled with this for days now. I want to add data from Firebase into array, I have created json file with list of categories and imported in firebase.

My JSON file look like this:

 {
  "Category" : [ {
    "categoryId" : "1",
    "imageName" : "cat_001.png",
    "title" : "CAT"
  }, {
    "categoryId" : "2",
    "imageName" : "dog_001.png",
    "title" : "DOG"
  }, {
    "categoryId" : "3",
    "imageName" : "fish_001.png",
    "title" : "FISH"
  }, {
    "categoryId" : "4",
    "imageName" : "bird_001.png",
    "title" : "BRID"
  }]
}

Firebase database looks like this

Category class looks like this

struct Category {

    private(set) public var title: String
    private(set) public var imageName: String


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

I use custom cell to show my data and here is my custom cell class

class CategoryCell: UITableViewCell {

    @IBOutlet weak var categoryImage: UIImageView!
    @IBOutlet weak var categoryTitle: UILabel!

    func updateViews(category: Category){
        categoryImage.image = UIImage(named: category.imageName)
        categoryTitle.text = category.title
    }
}

And I use DataService class to get data, right now data is hard coded and its working fine.

  class DataService{
        static let instance = DataService()

// How to add data from firebase in here`?
        private let categories = [Category(title: "CAT", imageName: "cat_001"),
                                  Category(title: "DOG", imageName: "dog_001"),
                                  Category(title: "FISH", imageName: "fish_001")]

        func getCategories() -> [Category]{
            return categories

        }
    }

and finally here is my ViewController

class CategoriesVC: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var categoryTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        categoryTable.dataSource = self
        categoryTable.delegate = self
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell") as? CategoryCell {
            let category = DataService.instance.getCategories()[indexPath.row]
            cell.updateViews(category: category)
            return cell
        }else{
            return CategoryCell()
        }
    }
}

I am going to add more categories in the future. With hard coded data my app looks like this and i want to achieve same result with data from firebase.

1 Answer 1

1

Try it like this, just use an array of Category's for the tableview datasource:

var tableData = [Category]()

then in viewDidLoad, set up a firebase observer to update that array any time there are changes to the Category node in firebase:

ref.child("Category").observe(.value, with: { snapshot in
    var newTableData: [Category] = []

    for category in snapshot.children {

        let dict = category.value as! [String: AnyObject]

        let title     = dict["title"] as! String
        let imageName = dict["imageName"] as! String

        let newCategory = Category(title: title, 
                               imageName: imageName)

        newTableData.append(newCategory)
    }

    self.tableData = newTableData
    self.tableview.reloadData()
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer @meggar, but i dont quit understand where to put this code and what to do. :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.