在使用CLGeocoder时,我发现崩溃(EXC_BAD_ACCESS)就在我不明白的封闭成功部分中的let placemark ...之后。我正在测试,可能已尝试多次访问服务器。或者我是否需要在后台线程中进行调用?
import UIKit
import CoreLocation
class ViewController: UIViewController {
var destinationPlacemark = CLPlacemark()
override func viewDidLoad() {
super.viewDidLoad()
forwardGeocoding(address: "Infinite Loop, Cupertino, CA 95014")
}
func forwardGeocoding(address: String) {
CLGeocoder().geocodeAddressString(address, completionHandler: { (placemarks, error) in
if error != nil {
print(error ?? "Error in plscement conversion")
return
}
if (placemarks?.count)! > 0 {
let placemark = placemarks?[0]
let location = self.destinationPlacemark.location
let coordinate = location?.coordinate
print("Latitude: \(coordinate!.latitude), Longitude: \(coordinate!.longitude)")
self.destinationPlacemark = placemark!
}
})
}
}
答案 0 :(得分:0)
*已更新为原因*
你这里有很多东西,所以我会尝试逐步完成修改它的修改:
首先,它为什么会崩溃:
使用以下命令创建destinationPlacemark:
var destinationPlacemark = CLPlacemark()
所以当它运行时:
let location = self.destinationPlacemark.location
它针对不包含位置数据的空地标运行。通过从保护语句中创建的检索到的地标中提取位置,可以避免此问题。
接下来,工作代码:
import UIKit
import CoreLocation
class ViewController: UIViewController {
var destinationPlacemark: CLPlacemark?
override func viewDidLoad() {
super.viewDidLoad()
forwardGeocoding(address: "1 Infinite Loop, Cupertino, CA 95014")
}
func forwardGeocoding(address: String) {
CLGeocoder().geocodeAddressString(address, completionHandler: { (placemarks, error) in
if error != nil {
print(error ?? "Error in pla conversion")
return
}
guard let placemark = placemarks?.first, let coordinate = placemark.location?.coordinate else { return }
print("Latitude: \(coordinate.latitude), Longitude: \(coordinate.longitude)")
self.destinationPlacemark = placemark
})
}
}
产生:
Latitude: 37.3316941, Longitude: -122.030127
destinationPlacemark
的变量,请参阅上面的正确设置