微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Swift]定位

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐