我的JSON树是:
"users" : {
"3iQrxqczoGRQVMLUWVZu3MvJNyh1" : {
"annotations" : {
"-Ku99FZpxfy1sFu_rbTR" : {
"BJ's Restaurant & Brewhouse" : {
"annotationSubtitle" : "5699 Newark CA",
"annotationTitle" : "BJ's Restaurant & Brewhouse",
}
},
"-Ku9IbvW65305uwu7UuE" : {
"Apple Infinite Loop" : {
"annotationSubtitle" : "1 Cupertino CA",
"annotationTitle" : "Apple Infinite Loop",
最初我已经能够使用此代码加载tableView。 for循环提取JSON树中的每个子节点,并将其附加到newAnnotations
,然后将其放入AnnotationListItem
,这是用于加载tableView
的本地数组。 AnnotationListItem
是我为保留annotationTitle
,annotationSubtitle
等而制作的结构,我会在loadList
中致电viewDidLoad
。 :
func loadList() {
if let uid = Auth.auth().currentUser?.uid {
uidRef.child(uid).child("annotations").observeSingleEvent(of: .value, with: {snapshot in
var newAnnotations: [AnnotationListItem] = []
for item in snapshot.children {
let annotationItem = AnnotationListItem(snapshot: item as! DataSnapshot)
newAnnotations.append(annotationItem)
}
annotationList = newAnnotations
self.tableView.reloadSections([0], with: .fade)
})
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return annotationList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath)
let annotatedItem = annotationList[indexPath.row]
cell.textLabel?.text = annotatedItem.annotationTitle
cell.detailTextLabel?.text = annotatedItem.annotationSubtitle
return cell
}
现在我在添加新注释时创建了childAutoID,并在this example后创建了一个数组来存储childAutoID'
func someFunc() {
guard let uid = Auth.auth().currentUser?.uid else { return }
uidRef.child(uid).child("annotations").observe( .childAdded, with: { (snapshot) in
var idKeys = [String]() //this will hold your keys
for snap in snapshot.children.allObjects {
let id = snap as! DataSnapshot
idKeys.append(String(id.key))
}
print(idKeys)
})
}
正确打印了idKeys,但现在我无法将此数组集成到原始代码中。我无法再访问AnnotationListItem
下的"annotations"
子节点,因为我必须通过childByAutoID
。我怎样才能做到这一点?如果它令人困惑,请告诉我,我会澄清。