我使用的顯示在表視圖中的問題的列表火力地堡構建應用程序的子數據。當用戶點擊一個問題(表格視圖中的一個單元格)時,該應用程序會跳到另一個視圖控制器,該控制器顯示與該問題關聯的答案列表。火力地堡的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