从Firebase获取数据 [英] Get data from Firebase
问题描述
我正在尝试从Firebase获取数据,我尝试过这样:
I am trying to get data from Firebase, I have 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 error in this line:
let data = snapshot.value as! NSDictionary
它说:无法转换类型'__NSArrayM'的值(0x10ebfc8d8 )到'NSDictionary'(0x10ebfcd60)。
来自Firebase的数据如下:
My data from Firebase like this:
但另一方面,我在另一个ViewController中使用另一个代码从Firebase获取用户名和角色,它有效。
But in other side, I use another code in another ViewController to get users name 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()
})
但为什么第一个代码总是崩溃。
But why the first code always crash.
任何帮助都将受到赞赏。谢谢。
Any helps would be appreciated. Thanks.
推荐答案
如果超过50%的密钥介于0和最大密钥之间,Firebase会将字典对象转换为数组(确切地说)你的情况只有一个零元素。)
Firebase transforms your dictionary object to an array if more than 50% of keys are between 0 and maximum key (exactly your case with one zero element).
https://www.firebase.com/docs/ios/guide/understanding-data.html#section-arrays-in-firebase
这篇关于从Firebase获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!