无法从Firebase获取价值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法从Firebase获取价值相关的知识,希望对你有一定的参考价值。
我正在尝试在我设置的Firebase数据库中获取值,但是我遇到了尝试将其解决的问题。在我的计划中有一个部分,我在Cities
下通过每个孩子,并获得每个城市的名称。我认为尝试获取同一部分中每个城市的状态是一个好主意,但我无法理解。下面是JSON对象的示例。我觉得我很亲密但却缺少一些可以把它放在一起的东西。
"Users" : {
"NPNBig20BXNpX4Rz0UbMyiKAarY2" : {
"Cities" : {
"New York City" : {
"Status" : "Empty"
},
"Atlanta" : {
"Status" : "Empty"
},
"Test City" : {
"Status" : "Wow",
"Value" : "Test"
}
},
"Email" : "fakeemail@gmail.com"
}
}
码:
guard let uid = userID else { return }
let databaseRef = Database.database().reference(fromURL: "https://testApp.firebaseio.com/").child("Users").child(uid).child("Cities")
var dataTest : [String] = []
//var cityDictionary: [String:String]()
databaseRef.observeSingleEvent(of: .value, with: {(snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
guard let value = snap.value else { return }
//let testData = value["Status"] **Type Any has no subscript
print("Key: ", key, "
Value: ", value)
dataTest.append(key)
}
completion(dataTest)
})
这是打印输出
Key: New York City
Value: {
Status = Empty;
}
Key: Sintra
Value: {
Status = Empty;
}
Key: Test City
Value: {
Status = Wow;
Value = Test;
}
答案
这是你从Status
获得value
的方式:
if let value = snap.value as? [String: AnyObject] {
let Status = value["Status"] as? String ?? ""
}
您的完整代码将是:
guard let uid = userID else { return }
let databaseRef = Database.database().reference(fromURL: "https://testApp.firebaseio.com/").child("Users").child(uid).child("Cities")
var dataTest : [String] = []
//var cityDictionary: [String:String]()
databaseRef.observeSingleEvent(of: .value, with: {(snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
guard let value = snap.value else { return }
//let testData = value["Status"] **Type Any has no subscript
if let value = snap.value as? [String: AnyObject] {
let Status = value["Status"] as? String ?? ""
}
print("Key: ", key, "
Value: ", value)
dataTest.append(key)
}
completion(dataTest)
})
另一答案
func handleGetCities(_ completion: @escaping ([String]) -> ()) {
guard let uid = Auth.auth().currentUser?.uid else { return }
// OR
guard let uid = userID else { return }
// THEN
var data: [String] = []
let reference = Database.database().reference()
reference.child("Users").child(uid).child("Cities").observe(.childAdded, with: { (snapshot) in
let city_name = snapshot.key
data.append(city_name)
completion(data)
}, withCancel: nil)
}
以上是关于无法从Firebase获取价值的主要内容,如果未能解决你的问题,请参考以下文章