gpt4 book ai didi

ios - 如何访问 childByAutoID 下的 Firebase 数据?

转载 作者:可可西里 更新时间:2023-11-01 00:55:02 25 4
gpt4 key购买 nike

我目前正在尝试访问一些以随机子 ID 放入我的数据库中的图书数据。我一直在搜索其他问题,但我得到的最远的是能够在闭包中访问 ID。我不知道如何正确设置完成处理程序来提取 ID。

另外,我不知道是否有更简单的方法来解决这个问题?

这是我尝试访问的数据: Firebase data

enter image description here

我认为这是我当前需要完成处理程序的代码?

func getChildID(department: String, course: String) {

let parentRef = myDatabase.child("departments").child(department).child(course)

parentRef.observeSingleEvent(of: .value) { (courseSnapshot) in
if let data = courseSnapshot.value as? [String:String] {

for value in data {
let isbn = value.value
if isbn != "ISBN" {

myDatabase.child("listings").child("\(isbn)").observeSingleEvent(of: .value, with: { (snapshot) in
let dictionary = snapshot.value as! NSDictionary
for key in dictionary.keyEnumerator() {
let myKey = key as! String
return
}
})
}
}
}
}
}

最佳答案

我们开始吧。问题的答案。但是,我在对该问题的评论中提到,结构可以改进。但是,每个列出的 child 下可能有更多的 child ,所以这个答案会处理它。

这只是打印每个作者的姓名,但它显示了如何获取它,因此应该为其他子节点扩展答案。

let listingsRef = self.ref.child("listings")
listingsRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let autoIdSnap = child as! DataSnapshot
for autoChild in autoIdSnap.children {
let childSnap = autoChild as! DataSnapshot
let dict = childSnap.value as! [String: Any]
let author = dict["author"] as! String
print(author)
}
}
})

哦,还有一个更好的结构可能是

listings
childByAutoId
author: "Some author"
listing: 9780184888
childByAutoId
author: "Another author"
listing: 9799292598

编辑:如果每个列表下只有一个 childByAutoId,您可以消除上面的循环并执行此操作

let listingsRef = self.ref.child("listings")
listingsRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let autoIdSnap = child as! DataSnapshot //each listing
let childDict = autoIdSnap.value as! [String: Any] //a dict of items within the listing
let firstKey = childDict.keys.first! //the key to the first item
let valuesDict = childDict[firstKey] as! [String: Any] //the values for that key
let author = valuesDict["author"] as! String //the author value
print(author)
}
})

关于ios - 如何访问 childByAutoID 下的 Firebase 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51778915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com