2016-06-20 121 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