である私は、地図上にすべての私の注釈をロード.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)
}
}
と私はのエラーを取得:
はの値をキャストできませんでした'NSDictionary'(0x1060b92d8)に '__NSCFString'(0x1060b84f0)を入力します。 snapshotValueの印刷の説明: ([String:AnyObject])snapshotValue =変数が使用できません>
この問題を解決するにはどうすればよいですか?
UPDATE
.observe(.value)
作品。しかし、なぜ私はまだ.childAdded
がいないのだろうと思っています
を取得するには、このいただきありがとうございます!ちょうど明らかであるように、私はもともと、.childAddedがすべての既存の子を一度走ってから、追加されたすべての子のリスナーとして振る舞ったと考えました。それは間違っていますか?次に、 'viewDidLoad'で' loadAnnotations'関数を呼び出し、その下で 'annotationChildAdded'を呼び出しますか? – zachenn
よろしくお願いします。あなたは正しいのですが、最初はすべての既存の子を一度実行してから、追加されたすべての子がトリガーされます。しかしどちらの場合も、その特定の子のみを返し、内部にすべてのコンテンツを持つ親ノード全体を返しません。 – Alex
2番目の質問では、viewDidAppearメソッドで子追加メソッドを記述し、viewDidDisAppearメソッドですべてのオブザーバを削除することをお勧めします。また、childAddedオブザーバを呼び出す前に、配列内にあるすべての要素を削除して、ビューコントローラが表示されるたびに重複を避ける必要があります。 – Alex