查找选定的MapKit注释的postID

时间:2018-11-26 07:19:38

标签: ios swift firebase mapkit geofire

我正在尝试在 didSelect 上设置所选MapKit的注释ID(在我的情况下为mapEventID),并在Swift准备segue时使用:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   let postViewVC = segue.destination as! PostView
   postViewVC.eventID = mapEventID
}

mapEventID 在GeoFire观察器中初始化:

func retrieveAllEvents () {

    let postDB = Database.database().reference().child("DBName")

    postDB.observe(.childAdded) { (snapshot) in

        let snapshotValue =  snapshot.value as! Dictionary <String,AnyObject>
        let postTitle = snapshotValue ["EventTitle"]!
        let postLocation = snapshotValue ["VisibleLocation"]!
        let eventID = snapshotValue ["EventID"]
        let postTime = snapshotValue ["EventDateTimeStart"]!

        let date = self.convertTimestamp(serverTimestamp: postTime as! Double)
        let mapEventDetails : String  = "\(date) - \(postLocation)"

        self.geoFire.getLocationForKey(locationID! as! String) { (location, error) in
            if (error != nil) {
                print("An error occurred getting the location for eventID:", eventID as Any)

            } else if (location != nil) {

                let postLat = location?.coordinate.latitude
                let postLong = location?.coordinate.longitude
                let coordinate = CLLocationCoordinate2D(latitude: postLat!, longitude: postLong!)
                let annotation = EventAnnotation (coordinate: coordinate, withKey: eventID as! String, title: mapEventDetails, subtitle: mapEventDetails)

                self.mapEventID = annotation.eventKey
                self.eventMap.addAnnotation(annotation)

            } else {
                print("GeoFire does not contain a location for:", eventID as Any)
            }
        }
    }
}

问题在于它总是使用最新添加的帖子ID作为mapEventID,而不是用户实际点击的ID。这是有道理的,因为当通过观察者从Firebase检索ID时,它会“观察”所有密钥,而最新的则成为ID。

当用户点击注释时,如何获取特定于 的mapEventID?目前,我有:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    mapEventID = //How do I change the EventID here?
} 

我希望可以在Geofire观察器中将ID添加到注释的Description'属性中,但是Swift在以下方面不提供任何语法:

let annotation = EventAnnotation (coordinate: coordinate, withKey: eventID as! String, title: postTitle, subtitle: eventDetails)

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let annotation = view.annotation as? EventAnnotation {
        mapEventID = annotation.eventKey
    }
}