CLLocation定位

import UIKit

import CoreLocation

typealias LocationClosure = ((_ sheng: String, _ shi: String, _ qu: String)->Void)

class CLLocationTool: NSObject {

    

    public static let `default` = CLLocationTool.init()

    

    /// 定位

    var locationManager: CLLocationManager = CLLocationManager()

    var currLocation: CLLocation!

    var longitude: Double = 0

    var latitude: Double = 0

    

    /// 省

    var sheng: String = ""

    /// 市

    var shi: String = ""

    /// 区

    var qu: String = ""

    var locationClosure: LocationClosure?

    

    override init() {

        super.init()

        NotificationCenter.default.addObserver(self, selector: #selector(enterFore), name: UIApplication.willEnterForegroundNotification, object: nil)

    }

    

    @objc func enterFore() {

        setupManager()

    }

    

    deinit {

        print("deinit")

        NotificationCenter.default.removeObserver(self)

    }

        

    class func showLocate(_ locationClosure: LocationClosure?) {

        let location = CLLocationTool.default

        location.setupManager()

        location.locationClosure = { (sheng, shi, qu)->Void in

            locationClosure?(sheng, shi, qu)

        }

    }

    

    /// 用户权限提醒框

    func showAuthAlert() {

        let alertVC = UIAlertController.init(title: "定位服务未开启", message: "打开定位开关以享受更精准服务\n请进入系统设置>隐私>定位服务中打开开关,并允许App使用定位服务", preferredStyle: .alert)

        let settingAction = UIAlertAction(title: "设置", style: .default) { [weak self] action in

            self?.openAppSetting()

            print("去打开定位权限")

        }

        alertVC.addAction(settingAction)

        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { [weak self] action in

            guard let weakSelf = self else {return}

            weakSelf.locationClosure?("空", "空", "空")

        }

        alertVC.addAction(cancelAction)

        getCurrentVCBS2().present(alertVC, animated: true, completion: nil)

    }

    

    /// 打开页面的设置页面

    func openAppSetting() {

        if let openUrl = URL.init(string: UIApplication.openSettingsURLString) {

            if UIApplication.shared.canOpenURL(openUrl) {

                if UIApplication.shared.canOpenURL(openUrl) {

                    if #available(iOS 10.0, *) {

                        UIApplication.shared.open(openUrl, options: [:]) { (result) in

                            print("result----\(result)")

                        }

                    } else {

                        UIApplication.shared.openURL(openUrl)

                    }

                }

                

            }

        }

    }

    

}

extension CLLocationTool: CLLocationManagerDelegate {

    func setupManager() {

        let status = CLLocationManager.authorizationStatus()

        if (CLLocationManager.locationServicesEnabled() == false) || (status == .denied) || (status == .restricted) {

            showAuthAlert()

            return

        }

        locationManager.requestAlwaysAuthorization()

        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        locationManager.distanceFilter = 1000

        locationManager.requestAlwaysAuthorization()

        locationManager.requestWhenInUseAuthorization()

        locationManager.delegate = self

        locationManager.startUpdatingLocation()

    }

    

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let location: CLLocation = locations.last!

        longitude = location.coordinate.longitude

        latitude = location.coordinate.latitude

        if location.horizontalAccuracy > 0 {

            lonlatToCity(location)

            locationManager.stopUpdatingLocation()

        }

    }

    

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

        if let clError = error as? CLError {

            let status = CLLocationManager.authorizationStatus()

            if (CLLocationManager.locationServicesEnabled() == false) || (status == .denied)/* || (status == .restricted)*/ {

                locationClosure?("空", "空", "空")

            }

        }

        

        

    }

    

    func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {

        print("error---\(error)")

    }

    

    @available(iOS 14.0, *)

    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {

        let status = CLLocationManager.authorizationStatus().rawValue

        let status1 = manager.authorizationStatus.rawValue

        print("locationManagerDidChangeAuthorization---\(status)--\(status1)")

    }

    

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        print("didChangeAuthorization---\(status.rawValue)")

    }

    

    func lonlatToCity(_ location: CLLocation) {

        let geocoder: CLGeocoder = CLGeocoder()

        geocoder.reverseGeocodeLocation(location) { [weak self](placemarks, error) in

            

            guard let weakSelf = self, let tempMark = placemarks else { return }

//            if tempMark.count > 0 && (error == nil) {

//                let mark = tempMark.last

//                var sheng = mark?.administrativeArea ?? ""

//                // 四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)

//                var shi = mark?.locality ?? ""

//                let qu = mark?.subLocality ?? ""

//

//                if let city = mark?.locality {

//                    shi = city

//                } else {

//                    sheng = ""

//                    shi = mark?.administrativeArea ?? ""

//                }

//                print("\(sheng)\(shi)\(qu)")

//

//            } else if error == nil && tempMark.count == 0 {

//                print("没有解析到地理位置信息")

//            } else if error != nil {

//                print("error---\(String(describing: error))")

//            }

//

            if error == nil {

                

                let mark = placemarks?.last

                

                weakSelf.sheng = mark?.administrativeArea ?? ""

                // 四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)

                weakSelf.shi = mark?.locality ?? ""

                weakSelf.qu = mark?.subLocality ?? ""

                

                if let city = mark?.locality {

                    weakSelf.shi = city

                } else {

                    weakSelf.shi = mark?.administrativeArea ?? ""

                }

                print("\(weakSelf.sheng)\(weakSelf.shi)\(weakSelf.qu)")

            } else {

                print("位置转换失败--")

            }

            weakSelf.locationClosure?(weakSelf.sheng, weakSelf.shi, weakSelf.qu)

        }

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值