【发布时间】:2018-03-14 11:14:10
【问题描述】:
我的目标是构建一个简单的应用程序:
- 通过从
Firebase获取项目而拥有UITableViewCells。 - 每个单元格在被点击时执行到另一个
ViewController的转场。 - 在提供的
ViewController中显示获取项目的更多详细信息。
到目前为止我所做的工作:
- 我可以成功地从数据库中获取数据并将其放入字典中。我还可以根据这些数据填充
UITableViewCells。 - 点击时,单元格会根据需要显示一个新的
ViewController。
问题是,无论我点击哪个单元格,我的ViewController 总是显示Firebase 数据库中最近最少添加的项目。让我提供我的数据库结构和我的 Swift 代码:
Firebase 结构:
simple-app:
└── upcoming:
└── fourth:
└── desc: "description for the fourth item"
└── name: "fourth item"
└── third:
└── desc: "description for the third item"
└── name: "third item"
└── second:
└── desc: "description for the second item"
└── name: "second item"
└── first:
└── desc: "description for the first item"
└── name: "first item"
Swift 代码:
import Foundation
import UIKit
import Firebase
class Upcoming: UITableViewController{
@IBOutlet weak var upcomingItems: UITableView!
var itemName: String?
var itemDesc: String?
var ref: DatabaseReference!
var refHandle: UInt!
var itemList = [Item]()
let cellId = "cellId"
override func viewDidLoad() {
ref = Database.database().reference()
fetchItems()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
itemName = itemList[indexPath.row].name
itemDesc = itemList[indexPath.row].desc
cell.textLabel?.text = itemName
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "DetailedInfo", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DetailedInfo" {
var vc = segue.destination as! DetailedInfo
vc.name = itemName
vc.desc = itemDesc
}
}
func fetchItems(){
refHandle = ref.child("upcoming").observe(.childAdded, with: {(snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
print(dictionary) // dictionary is as desired, no corruption
let item = Item()
item.setValuesForKeys(dictionary)
self.itemList.append(token)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
})
}
}
我可以根据需要看到具有四个不同名称的四个不同单元格,但无论点击哪个单元格,下一个ViewController 显示最近最少添加项目的name 和desc 值,即first,从数据库。任何想法都可以解决这个问题。
【问题讨论】:
标签: swift firebase dictionary firebase-realtime-database