【发布时间】:2017-11-21 22:54:17
【问题描述】:
我是 Swift 的新手。我知道如何从 Firebase 获取一条数据,但是当我尝试将数据列表放入数组时,我没有收到错误或没有数据。请帮我。我已经为此苦苦挣扎了好几天。 我想将 Firebase 中的数据添加到数组中, 我已经创建了带有类别列表的 json 文件并在 firebase 中导入。
我的 JSON 文件如下所示:
{
"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 数据库看起来像 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
}
}
我使用自定义单元格来显示我的数据,这是我的自定义单元格类
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
}
}
我使用 DataService 类来获取数据,现在数据是硬编码的并且工作正常。
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
}
}
最后是我的 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()
}
}
}
我将在未来添加更多类别。 使用硬编码数据,我的应用程序看起来像 this,我想使用来自 firebase 的数据实现相同的结果。
【问题讨论】:
标签: ios swift firebase firebase-realtime-database