Optional(Error Domain=kCLErrorDomain Code=8 "(null)")定位好像失敗了哦
過程
開發(fā)中需要通過已有的經(jīng)緯度獲取地圖信息,iOS提供有相關(guān)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
//這個(gè)是城市
let city: String = (mark.addressDictionary! as NSDictionary).value(forKey: "City") as! String
//這個(gè)是國(guó)家
let country: String = (mark.addressDictionary! as NSDictionary).value(forKey: "Country") as! String
//這個(gè)是國(guó)家的編碼
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
//這是區(qū)
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))" + "定位好像失敗了哦")
}
}
}`
運(yùn)行,得到題圖的報(bào)錯(cuò)衅胀。
結(jié)果
再次搜索錯(cuò)誤內(nèi)容冯丙,此處注意kCLErrorDomain Code=8,別人kCLErrorDomain Code=0的就不用看了永品,那個(gè)錯(cuò)好像是沒有定位權(quán)限的意思做鹰。
在CocoaChina找到答案:
錯(cuò)誤8是代表 "kCLErrorGeocodeFoundNoResult" 也就是返回值為空。 我推測(cè)你是不是搜索的設(shè)置問題鼎姐,導(dǎo)致蘋果服務(wù)器返回空钾麸,也就是找不到對(duì)應(yīng)的地址。多試下炕桨,換下參數(shù)饭尝,還可以打印出傳的參數(shù)
再檢查我的代碼,找到問題:
let currLocation:CLLocation = CLLocation.init(latitude: longitude, longitude: latitude)
經(jīng)緯度傳反了献宫,所以不是一個(gè)有效的地址钥平,這個(gè)錯(cuò)不是第一次犯了,以前用oc的時(shí)候沒少吃虧姊途。改成:
let currLocation:CLLocation = CLLocation.init(latitude: latitude, longitude: longitude)
完