2016-06-20 119 views
1

我正在嘗試創建用戶所屬聊天的tableView。我在他們的網站上關注了firebase教程,他們說可以輕鬆獲得用戶是創建孩子的一部分聊天室列表,併爲該孩子添加房間名稱。Swift和Firebase查詢數據庫

所以我的結構看起來像這樣

Users 
    UNIQUE KEY 
     nickname: "name" 
     rooms 
      name: true 
Room 
etc etc 

所以在我cellForRow我用這個代碼

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 

    firebase.child("users").child(fUID).observeSingleEvent(of: .value, with: { snapshot in 
     for user in snapshot.children.allObjects as! [FIRDataSnapshot]{ 
      self.names = (user.value?["participating"] as? String)! 
     } 
    }) 

    cell.textLabel?.text = self.names 
    cell.detailTextLabel?.text = "test" 

    return cell 
} 

我得到一個錯誤,當我PO的名字就想出了一個空字符串

有人可以幫助我瞭解什麼是錯的,以及如何解決它?謝謝

編輯1

我得到的代碼部分工作

override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated) 

    let ref = firebase.child("users").child(fUID).child("participating") 

    ref.observeSingleEvent(of: .value, with: { snapshot in 

     print(snapshot.value) 

     var dict = [String: Bool]() 

     dict = snapshot.value as! Dictionary 

     for (key, _) in dict { 
      self.names = key 
      print(self.names) 
     } 

     self.rooms.append(self.names) 
     self.tableView.reloadData() 
    }) 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.rooms.count 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 

    cell.textLabel?.text = self.rooms[indexPath.row] 

    cell.detailTextLabel?.text = "test" 

    return cell 
} 

現在的問題是,有在火力2項......這是隻顯示一個其中

+0

我會觀察cellForRowAtIndexPath之外的整個數組。例如在viewDidAppear中。然後,一旦你有來自提取的項目重新加載tableview。 – DogCoffee

+0

我的問題是在行self.names ....我得到一個錯誤EXC_BAD_Instruction .... – RubberDucky4444

+0

您正在做的firebase的調用是在回調 - 所以你設置它的整個方式是錯誤的。將firebase調用移動到上述位置,而不是在該委託方法內。 – DogCoffee

回答

2

您使用的代碼是挑戰。下面是一個簡化版本:

let usersRef = firebase.child("users") 
let thisUser = usersRef.childByAppendingPath(fUID) 
let thisUsersRooms = thisUser.childByAppendingPath("rooms") 

thisUsersRooms.observeSingleEventOfType(.Value, withBlock: { snapshot in 

    if (snapshot.value is NSNull) { 
      print("not found") 
    } else { 
      for child in snapshot.children { 
       let roomName = child.key as String 
       print(roomName) //prints each room name 
       self.roomsArray.append(roomName) 
      } 

      self.myRoomsTableView.reloadData() 
    } 
}) 

話雖這麼說,這個代碼應該從內部viewDidLoad中作爲的tableView被刷新的數據應該從陣列中拉來填充cellView打電話來填充數組,然後。

+0

謝謝,像一個工作魅力 – RubberDucky4444

+0

@ RubberDucky4444太棒了!很高興幫助! – Jay