我试图使用Swift 3中的CLGeocoder生成格式化的完整地址.我引用了这个SO线程来获取下面给出的代码.
但是,有时应用程序崩溃时会出现"nil"错误:
//Address dictionary
print(placeMark.addressDictionary ?? "")
问题:
完整代码:
func getAddress() -> String {
        var address: String = ""
        let geoCoder = CLGeocoder()
        let location = CLLocation(latitude: selectedLat, longitude: selectedLon)
        //selectedLat and selectedLon are double values set by the app in a previous process
        geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
            // Place details
            var placeMark: CLPlacemark!
            placeMark = placemarks?[0]
            // Address dictionary
            //print(placeMark.addressDictionary ?? "")
            // Location name
            if let locationName = placeMark.addressDictionary!["Name"] …我有一个locationManager函数来获取用户当前位置并发布城市和州的名称.我有一个打印声明,所以我可以在我的控制台检查一切是否正常工作......就是这样.但是,它打印城市位置3次.这实际上在我的实际应用程序中引起了一个问题,但这超出了这个问题的范围.
我的功能如下:
var usersLocation: String!
var locationManager: CLLocationManager!
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation: CLLocation = locations[0]
    CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) -> Void in
        if error != nil {
            print(error)
        } else {
            let p = placemarks?.first // ".first" returns the first element in the collection, or nil if its empty
            // this code above will equal the first element in the placemarks array
            let city = p?.locality != nil ? p?.locality : ""
            let state = …