Get data from Firebase

I am trying to get data from Firebase, I tried like this:

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() } 

but it shows an error in this line:

 let data = snapshot.value as! NSDictionary 

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

My data from Firebase:

enter image description here

But on the other hand, I use different code in another ViewController to get the username and role from Firebase, it works.

 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() }) 

enter image description here

But why is the first code always crashing.

Any help would be appreciated. Thanks.

+5
source share
1 answer

Firebase converts a dictionary object into an array if more than 50% of the keys are between 0 and the maximum key (it is your case with one null element).

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

+1
source

Source: https://habr.com/ru/post/1245761/


All Articles