从Firebase

时间:2016-03-25 09:31:32

标签: ios 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的数据如下:

enter image description here

但另一方面,我在另一个ViewController中使用另一个代码来从Firebase获取用户名和角色,它可以工作。

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

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

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

1 个答案:

答案 0 :(得分:1)

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

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