将所有 firebase 数据加载到 mapView

Load all firebase data into mapView

我想制作一个地图应用程序,我的地点(“事件”)存储在 Firebase 数据库中。 Firebase 看起来像这样(示例):

我可以像这样显示数据库中的一个特定事件:

func plotEvents(){
    // Show event on map
    mapView.delegate = self
    database.child("event").observeSingleEvent(of: .value, with: {
        snapshot in
        guard let value = snapshot.value as? [String: Any] else{
            return
        }
        let coordinates = CLLocationCoordinate2D(latitude: (value["latitude"] as! CLLocationDegrees), longitude: value["longitude"] as! CLLocationDegrees)
        let event2 = Event(title: value["title"] as? String, locationName: value["location"] as? String, discipline: value["discipline"] as? String, coordinate: coordinates)
        self.mapView.addAnnotation(event2)
    })
}

现在我尝试修改我的函数以显示数据库中的所有事件。有人可以帮我弄这个吗? :)

谢谢!

您需要从事件集合中获取所有事件,然后遍历所有事件并添加它们。

   let db = Firestore.firestore()
   db.collection("Events").getDocuments { (snapshot, error) in
        if let documents = snapshot?.documents {
               for document in documents {
                    let coordinates = CLLocationCoordinate2D(latitude: (value["latitude"] as! CLLocationDegrees), longitude: value["longitude"] as! CLLocationDegrees)
                    let event = Event(title: value["title"] as? String, locationName: value["location"] as? String, discipline: value["discipline"] as? String, coordinate: coordinates)
                    self.mapView.addAnnotation(event)
               }
         }
    }