Optional(Error Domain=kCLErrorDomain Code=8 "(null)")定位好像失败了哦
过程
开发中需要通过已有的经纬度获取地图信息,iOS提供有相关API,搜索找到代码,略作修改,抄录如下:
` func lonLatToAddress() {
let currLocation:CLLocation = CLLocation.init(latitude: longitude, longitude: latitude)
let geocoder: CLGeocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(currLocation) { (placemark, error) -> Void in
if(error == nil) { //成功
let array = placemark! as NSArray
let mark = array.firstObject as! CLPlacemark
//这个是城市
let city: String = (mark.addressDictionary! as NSDictionary).value(forKey: "City") as! String
//这个是国家
let country: String = (mark.addressDictionary! as NSDictionary).value(forKey: "Country") as! String
//这个是国家的编码
let countryCode: String = (mark.addressDictionary! as NSDictionary).value(forKey: "CountryCode") as! String
//这是街道位置
let formattedAddressLines: String = ((mark.addressDictionary! as NSDictionary).value(forKey: "FormattedAddressLines") as AnyObject).firstObject as! String
//这是具体位置
let address: String = (mark.addressDictionary! as NSDictionary).value(forKey: "Name") as! String
//这是省
let state: String = (mark.addressDictionary! as NSDictionary).value(forKey: "State") as! String
//这是区
let subLocality: String = (mark.addressDictionary! as NSDictionary).value(forKey: "SubLocality") as! String
self.city = city
self.address = address
self.country = country
self.countryCode = countryCode
self.formattedAddressLines = formattedAddressLines
self.state = state
self.subLocality = subLocality
}else {
print("\(String(describing: error))" + "定位好像失败了哦")
}
}
}`
运行,得到题图的报错。
结果
再次搜索错误内容,此处注意kCLErrorDomain Code=8,别人kCLErrorDomain Code=0的就不用看了,那个错好像是没有定位权限的意思。
在CocoaChina找到答案:
错误8是代表 "kCLErrorGeocodeFoundNoResult" 也就是返回值为空。 我推测你是不是搜索的设置问题,导致苹果服务器返回空,也就是找不到对应的地址。多试下,换下参数,还可以打印出传的参数
再检查我的代码,找到问题:
let currLocation:CLLocation = CLLocation.init(latitude: longitude, longitude: latitude)
经纬度传反了,所以不是一个有效的地址,这个错不是第一次犯了,以前用oc的时候没少吃亏。改成:
let currLocation:CLLocation = CLLocation.init(latitude: latitude, longitude: longitude)
完