首先我們必須明確的一點是碟婆,我們在使用其他框架拄踪,不管是原生的還是第三方的含思,我們都需要導(dǎo)入庫城瞎。然后我們才能進行之后的操作
導(dǎo)入CoreLocation##
選中項目渤闷,然后選擇target中的Bulding Phases選擇Link Binary With Libraries,點擊加號,然后搜索CoreLocation即可
點擊屏幕按鈕實現(xiàn)CLLocationManagerDelegate###
@IBAction func BtnClicked(_ sender: UIButton) {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
CoreLOcation的代理方法
//定位失敗的方法
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.locationLab.text = "Error while updating location " + error.localizedDescription
}
//更新定位的方法
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
self.locationLab.text = "Reverse geocoder failed with error" + error!.localizedDescription
return
}
if placemarks!.count > 0 {
let pm = placemarks![0]
self.displayLocationInfo(placemark: pm)
} else {
self.locationLab.text = "Problem with the data received from geocoder"
}
})
}
func displayLocationInfo(placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
self.locationLab.text = String.init(format: "\(locality)+\(postalCode)+\(administrativeArea!)+\(country!)")
}
}
最后選擇在真機和數(shù)據(jù)流量的環(huán)境下測試脖镀,那樣測試出來的數(shù)據(jù)會更加準確飒箭。
代碼請戳原生地圖CoreLocation的使用