SWIFT:为什么我的 URL 地图应用无法正常工作?

SWIFT: Why isn't my URL to maps app working correctly?

我有代码让用户点击注释,然后单击一个按钮,通过将它们发送到地图应用程序,为他们提供所述注释所在城市的方向。这是代码:

@IBAction func routingButton(_ sender: UIButton) {

    let annotationAsCLLocation = CLLocation(latitude: coordinatesInTransition.latitude, longitude: coordinatesInTransition.longitude)
    
     geoCoder.reverseGeocodeLocation(annotationAsCLLocation) { (clPlacemark, error) in
         //print("Reverse geocoding resulted in an error: \(error ?? "" as! Error)")
        
        // I found the URL strings documentation for opening the route in the Maps app here: https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html
        if let url = URL(string: "http://maps.apple.com/?daddr=\(clPlacemark?[0].locality)&dirflg=d&t=m") {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
     }
}
// Create function that uses the distanceTo and determines which aspect of the placemark is the closest to the annotation and uses that for the URL
}

无论如何,当我输入创建的 CLPlacemark 的位置 (clPLacemark?[0].locality) 时,URL 不会将我发送到地图应用程序,但是当我输入原始的相同位置,例如 URL(string: "http://maps.apple.com/?daddr=Hague&dirflg=d&t=m") 与正常方式相反,URL(string : "http://maps.apple.com/?daddr=(clPlacemark?[0].locality)&dirflg=d&t=m"),有效。

本质上,用实际名称替换通过地标访问的编码位置是可行的,但编码方式不是。知道为什么吗?谢谢

你应该处理可选项。

替换:

if let url = URL(string: "http://maps.apple.com/?daddr=\(clPlacemark?[0].locality)&dirflg=d&t=m") {

与:

if let url = URL(string: "http://maps.apple.com/?daddr=\(clPlacemark?[0].locality ?? "")&dirflg=d&t=m") {