从App打开地图返回Nil作为自定义点注释的位置标题

时间:2017-04-05 12:45:52

标签: ios swift xcode mapkit

我正在制作一个应用程序,其中包含多个自定义点注释列表,供我的合作伙伴和我参加婚礼。我最近想出了如何创建一个打开该地图的功能。问题是,当您点击标注时,路线标题显示未知位置或无。我有一个所有自定义点注释的标题集,我只是在地图上寻找被点击的注释的标题作为最终目的地标题。任何帮助深表感谢。这是我的第一个完整的应用程序,这是在启动和运行之前要弄清楚的最后一件事。在此先感谢您的帮助。如果问题不是来自此功能,请尽快提供更多代码。

    // Open maps app programatically
func mapView(_ mapView: MKMapView, annotationView view:MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    let placemark = MKPlacemark(coordinate: view.annotation!.coordinate, addressDictionary: nil)
    let mapItem = MKMapItem(placemark: placemark)
    let launchOptions = [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeTransit]
    view.canShowCallout = true
    self.title = title
    mapItem.name = title
    mapItem.openInMaps(launchOptions: launchOptions)
}

1 个答案:

答案 0 :(得分:0)

经过大量的研究并试图找出这个问题后,我终于找到了一个解决方案,它是对其他一些问题的几个不同答案的组合。以下是适合我的解决方案。我希望这可以帮助其他人。

    // Open maps app programatically
func openMapsAppWithDirections(to coordinate: CLLocationCoordinate2D, destinationName name: String) {
    let options = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
    let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: nil)
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = name // Provide the name of the destination in the To: field
    mapItem.openInMaps(launchOptions: options)
}

func mapView(_ MapView: MKMapView, annotationView: MKAnnotationView, calloutAccessoryControlTapped Control: UIControl) {

    if Control == annotationView.rightCalloutAccessoryView {
        if let annotation = annotationView.annotation {
            // Unwrap the double-optional annotation.title property or
            // name the destination "Unknown" if the annotation has no title
            let destinationName = (annotation.title ?? nil) ?? "Unknown"
            openMapsAppWithDirections(to: annotation.coordinate, destinationName: destinationName)
        }
    }
}