我有一个像这样的Firebase结构:
...
"objects" : {
"-M2ToRL-DOIL5B7Kq1JH" : {
"name" : "Orange",
"weight" : 50,
"color" : "Orange",
"objectID" : "-M2ToRL-DOIL5B7Kq1JH"
},
"-M2U20-rpaaWBWnXjirx" : {
"name" : "Banana",
"weight" : 20,
"color" : "Yellow",
"objectID" : "-M2U20-rpaaWBWnXjirx"
}
},
我想访问childByAutoID
键。我有这样的查询,但没有任何结果。
ref?.child("objects").queryOrdered(byChild:"name").queryEqual(toValue: name).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.exists() {
print(snapshot)
let value = snapshot.value as? NSDictionary
var key = ""
key = value?["objectID"] as? String ?? "Error"
} else {
return
}
}, withCancel: {(Error) in
print(Error.localizedDescription)
})
我也尝试获取value.key
,但未成功。我如何从孩子本身或从存储的objectID
值中获取密钥?
答案 0 :(得分:0)
如果要检索值"-M2ToRL-DOIL5B7Kq1JH"
,则需要迭代访问它:
ref?.child("objects").queryOrdered(byChild:"name").queryEqual(toValue: name).observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot]{
print(child.key);
if snapshot.exists() {
print(snapshot)
let value = snapshot.value as? NSDictionary
var key = ""
key = value?["objectID"] as? String ?? "Error"
} else {
return
}
}
}, withCancel: {(Error) in
print(Error.localizedDescription)
})
由于您的引用位于节点objects
上,因此要访问键,请使用for循环,然后使用属性key
在此处查看更多信息:
答案 1 :(得分:0)
如果您将childByAutoId用作密钥,通常没有理由在节点内复制该数据,因为您可以直接访问密钥。
例如
ref?.child("objects").queryOrdered(byChild:"name").queryEqual(toValue: name).observeSingleEvent(of: .value, with: { snapshot in
if snapshot.exists() == false {
print("none found, returning")
return
}
let allResults = snapshot.children.allObjects as! [DataSnapshot]
for snap in allResults {
print(snap.key) //prints each child key
}