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.