我使用的显示在表视图中的问题的列表火力地堡构建应用程序的子数据。当用户点击一个问题(表格视图中的一个单元格)时,该应用程序会跳到另一个视图控制器,该控制器显示与该问题关联的答案列表。火力地堡的iOS斯威夫特 - 检索对应的聊天对话ID
这是我是如何构建我的数据库的JSON树:
{
"answers": {
"question01": {
"answer01": {
"name": "kelly"
"text": "I'm doing great"
},
"answer02": {
"name": "george"
"text": "never been better"
}
}
},
"questions": {
"question01": {
"name": "courtney"
"text": "how are you?"
},
"question02": {
"name": "bob"
"text": "why is the earth round?"
}
}
我能够显示在第一表格中的问题,查看下面的代码没有问题:
// MARK: - Firebase Database Configuration
func configureDatabase() {//this method gets called in viewDidLoad
ref = FIRDatabase.database().reference()
//listen for new questions in the database
_refHandle = self.ref.child("questions").observeEventType(.ChildAdded, withBlock: {(snapshot) -> Void in
self.questionsArray.append(snapshot)
self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.questionsArray.count-1, inSection: 0)], withRowAnimation: .Automatic)
})
}
deinit {
self.ref.child("questions").removeObserverWithHandle(_refHandle)
}
// MARK: - UITableViewDataSource & UITableViewDelegate methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return questionsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell! = self.tableView.dequeueReusableCellWithIdentifier("tableViewCell", forIndexPath: indexPath)
//unpack question from database
let questionSnapshot: FIRDataSnapshot! = self.questionsArray[indexPath.row]
let question = questionSnapshot.value as! Dictionary<String, String>
let name = question[Constants.QuestionFields.name] as String!
let text = question[Constants.QuestionFields.text] as String!
cell!.textLabel?.text = name + ": " + text
cell!.imageView?.image = UIImage(named: "ic_account_circle")
if let photoUrl = question[Constants.QuestionFields.photoUrl], url = NSURL(string:photoUrl), data = NSData(contentsOfURL: url) {
cell!.imageView?.image = UIImage(data: data)
}
return cell!
}
继Firebase's guide to structuring data,我假设我需要检索相关的使用,在JSON树中的每个孩子都有共同的对话ID的问题的答案。例如:“question01”将是第一个问题的对话ID,它有两个答案。
我怎样才能检索到相关的每一个问题,这样我可以在以后显示在表视图这些答案应答数据?
只是要清楚,我不问如何在表视图中显示的数据,而是什么是从相关的一个问题的谈话ID我的火力地堡数据库检索应答数据的代码。
你想要一次回答所有答案吗?或者一次回答相应的问题? – triandicAnt
一些事情。 1)你可能不需要removeObserverWithHandle。它似乎只有有限的几个问题,所以我建议使用* observeSingleEventOfType(.Value)*来读取它们,然后迭代快照以将它们添加到表格中(除非您想要通知新问题,那么它很好)2)每个问题都有一个关键字:值对,关键字是问题的名称,即'question01'。当用户点击该问题时,使用与* answersSingleEventOfType *相同的代码来填充答案tableView。 – Jay
@ triple.s我想每次回答对应于一个特定的问题。例如,如果用户点击了“question01”,那么我就会发布上面提到的JSON树:“你好吗?”那么应用程序会延续到一个新的视图控制器,该视图控制器显示一个表视图,其中包含'question01'的两个答案,即“我做得很好”和“从未更好” – alexisSchreier