我试图在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)
}
}
}
}
问题是它总是使用最近添加的post的ID作为mapEventID,而不是用户实际使用的ID。这是有意义的,因为当通过观察者从Firebase检索ID时,它会“观察”所有的密钥,而最近的一个成为ID。
当用户点击注释时,如何获取特定的mapEventID?目前我有:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
mapEventID = //How do I change the EventID here?
}
我希望可以将ID添加到Geofire observer中注释的Description属性中,但是Swift没有提供任何语法:
let annotation = EventAnnotation (coordinate: coordinate, withKey: eventID as! String, title: postTitle, subtitle: eventDetails)
最佳答案
请尝试以下代码:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let annotation = view.annotation as? EventAnnotation {
mapEventID = annotation.eventKey
}
}