从Firebase获取数据

我试图从Firebase获取数据,我尝试过这样的:

FIREBASE_REF.childByAppendingPath("tasks").observeEventType(.Value, withBlock: { (snapshot) -> Void in print(snapshot.value) self.tasks = [Task]() var task = Task() let data = snapshot.value as! NSDictionary let tasksFromServer = data.allValues as! [NSDictionary] for taskFromServer in tasksFromServer { task.description = taskFromServer.objectForKey("description") as! String task.startTime = taskFromServer.objectForKey("startTime") as! String task.endTime = taskFromServer.objectForKey("endTime") as! String task.progress = taskFromServer.objectForKey("progress") as! Int let priorityTemp = taskFromServer.objectForKey("priority") as! Int switch priorityTemp { case 0: task.priority = .Low case 1: task.priority = .Medium case 2: task.priority = .High default: break } task.assignee = taskFromServer.objectForKey("assignee") as! String self.tasks.append(task) } MBProgressHUD.hideAllHUDsForView(self.view, animated: true) self.tableView.reloadData() } 

但是在这一行显示错误:

 let data = snapshot.value as! NSDictionary 

它说: Could not cast value of type '__NSArrayM' (0x10ebfc8d8) to 'NSDictionary' (0x10ebfcd60).

我的Firebase数据如下:

在这里输入图像说明

但是另一方面,我在另一个ViewController中使用另一个代码来从Firebase获取用户名和angular色,它起作用。

 FIREBASE_REF.childByAppendingPath("users").observeEventType(.Value, withBlock: { (snapshot) -> Void in self.names = [] self.roles = [] let data = snapshot.value as! NSDictionary let employees = data.allValues as! [NSDictionary] for employee in employees { let name = (employee.objectForKey("firstName") as! String) + " " + (employee.objectForKey("lastName") as! String) self.names.append(name) let role = employee.objectForKey("position") as! String self.roles.append(role) } MBProgressHUD.hideAllHUDsForView(self.view, animated: true) self.collectionView.reloadData() }) 

在这里输入图像说明

但为什么第一个代码总是崩溃。

任何帮助,将不胜感激。 谢谢。

如果超过50%的键位于0和最大键值之间,则Firebase会将字典对象转换为数组(如果您的情况只有一个零元素)。

https://www.firebase.com/docs/ios/guide/understanding-data.html#section-arrays-in-firebase