現在我有.observeSingleEvent(of: .value)
,我的所有註釋裝載到地圖:.oberve(.childAdded)產生錯誤,而.observeSingleEvent(作者:.value的)是不是
func loadAnnotations() {
if let uid = Auth.auth().currentUser?.uid {
uidRef.child(uid).child("annotations").observeSingleEvent(of: .value, with: { (snapshot) in
for item in snapshot.children {
// annotationListItem is a struct I created
let annotationItem = AnnotationListItem(snapshot: item as! DataSnapshot)
let doubleLatitude = Double(annotationItem.mapViewLatitude!)
let doubleLongitude = Double(annotationItem.mapViewLongitude!)
let coordinate = CLLocationCoordinate2DMake(doubleLatitude!, doubleLongitude!)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = annotationItem.annotationTitle
annotation.subtitle = annotationItem.annotationSubtitle
self.mapView.addAnnotation(annotation)
}
}, withCancel: nil)
}
}
現在我要地圖更新每次用戶添加一個新的註釋,所以我放在完全相同的代碼,但與.observe(.childAdded)
func annotationChildAdded() {
if let uid = Auth.auth().currentUser?.uid {
uidRef.child(uid).child("annotations").observe(.childAdded, with: { (snapshot) in
for item in snapshot.children {
let annotationItem = AnnotationListItem(snapshot: item as! DataSnapshot)
let doubleLatitude = Double(annotationItem.mapViewLatitude!)
let doubleLongitude = Double(annotationItem.mapViewLongitude!)
let coordinate = CLLocationCoordinate2DMake(doubleLatitude!, doubleLongitude!)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = annotationItem.annotationTitle
annotation.subtitle = annotationItem.annotationSubtitle
self.mapView.addAnnotation(annotation)
}
}, withCancel: nil)
}
}
我得到的錯誤:的
無法施展值鍵入'__NSCFString'(0x1060b84f0)爲'NSDictionary'(0x1060b92d8)。 快照的打印說明值: ([String:AnyObject])snapshotValue =變量不可用>
如何解決此問題?
UPDATE
.observe(.value)
作品。但我仍然想知道爲什麼.childAdded
不
謝謝!爲了清楚起見,我原本以爲'.childAdded'曾經遍歷所有現有的孩子,然後充當每個添加的孩子的監聽者。那是錯的嗎?其次,我應該在'viewDidLoad'中調用我的'loadAnnotations'函數,然後在它下面調用'annotationChildAdded'? – zachenn
不客氣@zachenn!你是對的,它最初確實貫穿所有現有的孩子,然後觸發每個孩子添加。但是在這兩種情況下,它只會返回該特定的子項,而不會返回包含其所有內容的整個父節點。我更新了我的答案,以便更容易理解 – Alex
對於第二個問題,我建議您在viewDidAppear方法中編寫子添加方法,並確保刪除viewDidDisappear方法中的所有觀察者。此外,在調用childAdded觀察者之前,您需要刪除陣列內的所有元素,以避免每次出現視圖控制器時都出現重複。 – Alex