英文:
Swift unable to retrieve child node firebase database
问题
let ref = Database.database().reference().child("category").child("subCat1")
ref.observeSingleEvent(of: .value) { (snapshot) in
for item in snapshot.children {
let snap = item as! DataSnapshot
let dict = snap.value as! [String: Any]
let storage = dict["storage"] as! String
print(storage)
}
}
英文:
My database looks like this
category
subCat1
item1
someData: somedata
storage: storageref
item2
someData: somedata
storage: storageref
item3
someData: somedata
storage: storageref
subCat2
item1
someData: somedata
storage: storageref
item2
someData: somedata
storage: storageref
item3
someData: somedata
storage: storageref
I would like to retrieve the value of the "storage" key in a specific subcategory node. I've tried tapping into one specific subcategory and retrieve to storage key with the following code:
let ref = Database.database().reference().child("category").child("subCat1")
ref.observeSingleEvent(of: .value) { (snapshot) in
for item in snapshot.children {
let snap = item as! DataSnapshot
let imageSnap = snap.childSnapshot(forPath: "storage")
let dict = imageSnap.value as! [String: Any]
let url = dict["storage"] as! String
print(url)
}
This code crashes the app on the line let dict = imageSnap.value as! [String: Any]
with the error code Could not cast value of type '__NSCFString' (0x10632a168) to 'NSDictionary' (0x10632b1a8)
I've tried printing snapshot, snapshot.child, snapshot.value etc. None of these give me what I'm looking for, they either do not work, or give me one large dictionary containing subCat1, all items, someData and storage.
Update:
with the help of Sh_Khan's answer below, I'm able to print the storage strings for each item in the node, however my for in loop causes the all the strings to be printed 3 times each so I get a total of 3 x 3 urls when I only want 3 (one for each item)
答案1
得分: 1
将以下部分替换为:
if let url = imageSnap.value as? String { }
英文:
Replace
let dict = imageSnap.value as! [String: Any]
let url = dict["storage"] as! String
with
if let url = imageSnap.value as? String { }
答案2
得分: 1
Sh_Khan的答案是正确的,只需尝试使用if let
解开项目值,以避免崩溃。您的更新代码如下:
let ref = Database.database().reference().child("category").child("subCat1")
ref.observeSingleEvent(of: .value) { (snapshot) in
for item in snapshot.children {
if let snap = item as? DataSnapshot {
let imageSnap = snap.childSnapshot(forPath: "storage")
let url = imageSnap.value as? String
print(url)
}
}
}
英文:
Above Sh_Khan answer is correct, just try to unwrap item value using if let
so you don't get crash. Your updated code below:
let ref = Database.database().reference().child("category").child("subCat1")
ref.observeSingleEvent(of: .value) { (snapshot) in
for item in snapshot.children {
if let snap = item as? DataSnapshot {
let imageSnap = snap.childSnapshot(forPath: "storage")
let url = imageSnap.value as? String
print(url)
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论