我想将包含纬度和经度值的用户位置反转为准确的地址。但是它不起作用,执行后返回空字符串。

另外,Xcode建议我使用CNPostalAddress,我不知道它是什么。

这是功能

import Foundation
import CoreLocation
import AddressBook`

    func reverseGeocoder()->String{
        let info:String?
        var geocoder = CLGeocoder()
        var currentUserLocation = CLLocation(latitude: 30, longitude: 122)
        geocoder.reverseGeocodeLocation(currentUserLocation, completionHandler: {
            (placemarks,error) -> Void in
            if placemarks != nil && placemarks?.count > 0{
                let placemark = placemarks![0] as CLPlacemark
                let addressDictionary = placemark.addressDictionary! as NSDictionary

                let str:NSMutableString = ""
                if let address = addressDictionary.objectForKey(kABPersonAddressStreetKey) as? String{
                    str.appendString(address)
                }

                if let state = addressDictionary.objectForKey(kABPersonAddressStateKey) as? String{
                    str.appendString(state)
                }

                if let city = addressDictionary.objectForKey(kABPersonAddressCityKey) as? String{
                    str.appendString(city)
                }

                info = str as String
            }
        }
        )
        return info
}

这是警告
ios - 如何将地理坐标转换为准确的地址?-LMLPHP

如果您能帮助我修复它,请感激:)

最佳答案

import AddressBook替换import Contacts并替换

addressDictionary.objectForKey(kABPersonAddressStreetKey)addressDictionary.objectForKey(CNPostalAddress.Street)
addressDictionary.objectForKey(kABPersonAddressStateKey)addressDictionary.objectForKey(CNPostalAddress.State)
addressDictionary.objectForKey(kABPersonAddressCityKey)addressDictionary.objectForKey(CNPostalAddress.City)
您可以在Apple Douments中获得更多信息

使用完成

func reverseGeocoder (completion: (info:String) -> Void){

    var geocoder = CLGeocoder()
    var currentUserLocation = CLLocation(latitude: 30, longitude: 122)
    geocoder.reverseGeocodeLocation(currentUserLocation, completionHandler: {
        (placemarks,error) -> Void in
        if placemarks != nil && placemarks?.count > 0{
            let placemark = placemarks![0] as CLPlacemark
            let addressDictionary = placemark.addressDictionary! as NSDictionary

            let str:NSMutableString = ""
            if let address = addressDictionary.objectForKey(kABPersonAddressStreetKey) as? String{
                str.appendString(address)
            }

            if let state = addressDictionary.objectForKey(kABPersonAddressStateKey) as? String{
                str.appendString(state)
            }

            if let city = addressDictionary.objectForKey(kABPersonAddressCityKey) as? String{
                str.appendString(city)
            }
            completion(info: str as String)

        }
    }
    )

关于ios - 如何将地理坐标转换为准确的地址?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39229190/

10-13 05:01