这是数据库
我正在尝试将isDisable追加到一个数组中
到目前为止,我所得到的是:
func retrieving(){
Database.database().reference().child("ServingHours/\(choosenDate)").observeSingleEvent(of: .value, with: {(snapshot) in
if let eachDict = snapshot.value as? NSDictionary{
for each in eachDict{
print(each.value)
}
}
}, withCancel: {(Err) in
})
}
控制台中的结果:
{
isDisable = false;
numberOfRegistration = 0;
}
{
isDisable = false;
numberOfRegistration = 0;
}
{
isDisable = false;
numberOfRegistration = 0;
}
{
isDisable = false;
numberOfRegistration = 0;
}
因此,我不知道如何从each.value
获取特定值
发布于 2019-07-15 07:05:46
您正在检索包含两个项(isDisable和numberOfRegistration)的特定日期对象。当您从Firebase中检索它们时,您使用"as?“将它们类型转换为NSDictionary。
您的值似乎是字符串格式,因此,您可以使用以下命令从NSDictionary中检索它们:
let isDisabled = eachDict["isDisable"] as? String
let numberOfRegistration = eachDict["numberOfRegistration"] as? String
你也可以直接在Firebase中将你的值设置为Bool或Int,并且你可以将检索到的对象类型转换为Bool (isDisable)和Int (numberOfRegistration)。但是现在看起来它们是字符串,所以你的代码应该是这样的:
func retrieving(){
Database.database().reference().child("ServingHours/\(choosenDate)").observeSingleEvent(of: .value, with: {(snapshot) in
if let eachDict = snapshot.value as? NSDictionary{
let isDisabled = eachDict["isDisable"] as? String
let numberOfRegistration = eachDict["numberOfRegistration"] as? String
print(isDisabled)
print(numberOfRegistration)
}
}, withCancel: {(Err) in
})
}
此外,如果您想要直接检索值,则不需要使用NSDictionary。您可以直接将检索到的值转换为您拥有的任何类型的对象。例如,假设您想要直接检索"isDisable“值:
func retrieving(){
Database.database().reference().child("ServingHours/\(choosenDate)").child("isDisable").observeSingleEvent(of: .value, with: {(snapshot) in
if let isDisable = snapshot.value as? String{
print(isDisable) }
查看针对Swift的Firebase官方文档:https://firebase.google.com/docs/database/ios/read-and-write
发布于 2019-07-15 12:25:36
您需要再次转换为字典(并且不使用NSDictionary)
if let eachDict = snapshot.value as? [String: AnyObject]{
for each in eachDict {
if let innerDict = each as? [String: AnyObject] {
//innerDict now contains isDisable and numberOfRegistration
if let isDisable = innerDict["isDisable"] as? String
print(isDisable)
}
if let numberOfRegistration = innerDict["numberOfRegistration"] as? String {
print(numberOfRegistration)
}
}
}
}
https://stackoverflow.com/questions/57030944
复制相似问题