一般使用系统提供的定位就能满足使用, 但有些需要获取adcode(区域编码)的需求就得接入高德地图来定位了.
Pods导入高德地图
#高德
pod 'AMapLocation'
// 使用系统定位
LocationHelper.shared.systemLocationManager()
// 使用高德地图定位
LocationHelper.shared.AMapLoactionManager { coor, result in
}
import Foundation
import CoreLocation
class LocationHelper: NSObject {
static let shared = LocationHelper()
/// 系统自带定位
var sysLocationManger = CLLocationManager()
/// 高德定位
private var amapLocationManger = AMapLocationManager()
typealias Success = (_ coordinate: CLLocationCoordinate2D?, _ isSuccess: Bool) -> Void
deinit {
debugPrint(#function, "释放了")
}
func systemLocationManager() {
self.sysLocationManger.delegate = self
self.sysLocationManger.desiredAccuracy = .leastNormalMagnitude
self.sysLocationManger.requestWhenInUseAuthorization()
self.sysLocationManger.startUpdatingLocation()
}
func amapLoactionManager(result: @escaping Success) {
self.amapLocationManger = AMapLocationManager()
self.amapLocationManger.pausesLocationUpdatesAutomatically = false
self.amapLocationManger.allowsBackgroundLocationUpdates = false
self.sysLocationManger.requestWhenInUseAuthorization()
self.amapLocationManger.desiredAccuracy = kCLLocationAccuracyHundredMeters
self.amapLocationManger.requestLocation(withReGeocode: true) { [weak self] (location, regecode, error) in
guard let this = self else { return }
if error != nil || location == nil {
this.sysLocationManger.requestWhenInUseAuthorization()
result(nil, false)
} else {
AppUserDefaults.shared.longitude = "\(location!.coordinate.longitude)"
AppUserDefaults.shared.latitude = "\(location!.coordinate.latitude)"
AppUserDefaults.shared.district = regecode?.district ?? ""
AppUserDefaults.shared.adcode = regecode?.adcode ?? ""
result(location?.coordinate, true)
}
this.amapLocationManger.stopUpdatingLocation()
}
}
}
extension LocationHelper : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let lo = locations.last{
self.sysLocationManger.stopUpdatingLocation()
let coordinate = lo.coordinate
AppUserDefaults.shared.longitude = "\(coordinate.longitude)"
AppUserDefaults.shared.latitude = "\(coordinate.latitude)"
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
debugPrint("定位失败")
}
}
原文地址:https://blog.csdn.net/u012881779/article/details/120924222
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。