[Swift]定位

郏博瀚
2023-12-01

一般使用系统提供的定位就能满足使用, 但有些需要获取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("定位失败")
    }
    
}
 类似资料: