【问题标题】:Find selected MapKit Annotation's postID查找选定的 MapKit Annotation 的 postID
【发布时间】:2018-11-26 07:19:37
【问题描述】:

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

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

ma​​pEventID 在 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)

【问题讨论】:

    标签: ios swift firebase mapkit geofire


    【解决方案1】:

    试试下面的代码:

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

    【讨论】:

    • 完美,我对 Annotation 和 AnnotationView 感到困惑 - 我试图将 AnnotationView 而不是 Annotation 转换为 EventAnnotation。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    相关资源
    最近更新 更多