CLLocationManager 需要强引用
var locationManager: CLLocationManager?
定位授权及相关处理
let clAuth = CLLocationManager.authorizationStatus()
switch clAuth {
case .notDetermined:
// 地理位置 选择
let manager = CLLocationManager()
locationManager = manager
manager.delegate = self
// 判断 定位信息的 授权情况
manager.requestAlwaysAuthorization()
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
case .denied, .restricted:
// Setting
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.openURL(url)
}
case .authorizedAlways, .authorizedWhenInUse:
// 地理位置 选择
let manager = CLLocationManager()
locationManager = manager
manager.delegate = self
manager.startUpdatingLocation()
}
CLLocation 代理、数据获取的处理
extension xxxx: CLLocationManagerDelegate {
//获取定位信息
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location: CLLocation = locations.last else {
return
}
if location.horizontalAccuracy > 0 {
let lat = Double(String(format: "%.0001f", location.coordinate.latitude)) ?? 0
let long = Double(String(format: "%.0001f", location.coordinate.longitude)) ?? 0
LonLatToCity(currLocation: location,lat: lat, long: long)
//停止定位
locationManager?.stopUpdatingLocation()
}
}
//出现错误
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
///将经纬度转换为城市名
func LonLatToCity(currLocation: CLLocation, lat: Double, long: Double) {
let geocoder: CLGeocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(currLocation) { [weak self](placemark, error) -> Void in
if(error == nil)
{
if let placeMark = placemark?.first {
if let addressDic: NSDictionary = placeMark.addressDictionary as NSDictionary? {
let cityName = addressDic.value(forKey: "City") as? String
let countryName = addressDic.value(forKey: "Country") as? String
self?.postMomentLocationCell?.cityName = cityName
self?.locationStruct = MomentLocationStruct(lat: lat, long: long,cityName: cityName, countryName: countryName)
}
}
// "CountryCode", "FormattedAddressLines", "Name", "State", "SubLocality"
}
}
}
}
网友评论