如何解决SWIFT:为什么我的地图应用程序URL不能正常工作?
我有一段代码,用户可以在其中点击注释,然后单击一个按钮,该按钮会将其发送到“地图”应用,从而向其指示该注释所在的城市的方向。这是代码:
@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,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") {
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。