CLLocation定位

CLLocation定位importUIKitimportCoreLocationimportAlamofiretypealiasLocationClosure=((_sheng:String,_shi:String,_qu:String)->Void)classCLLocationTool:NSObject{publicstaticlet`default`=CLLocationTool.init()///定…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

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)

        }

    }

}

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

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/158804.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 请写出用Graphics2D类的新方法画一个图形的步骤(表格如何画斜线)

    在机器人需要发表格图片需求,我搜索了一些第三方包,最终使用了java内置的Graphics2D来画表格生成jpg图片,再通过cq语句发送。表格图片,需要有标题,表格头,表格内容,将表格头和表格前三名设置背景色。使用Graphics2D画图,需要画横线,竖线,还有字体,其中选择位置进行渲染比较繁琐。所以我将画表格分为几部分来画1、先定图片大小图片的高…

    2022年4月13日
    48
  • XGBoost实战

    XGBoost实战1.XGBoost参数1.1常规参数GeneralParameters      booster[default=gbtree]:选择基分类器,可以是:gbtree,gblinear或者dart。gbtree和draf基于树模型,而gblinear基于线性模型。     &nbsp…

    2022年5月22日
    54
  • 梯度下降与随机梯度下降概念及推导过程「建议收藏」

    梯度下降与随机梯度下降概念及推导过程「建议收藏」接前一章:常用算法一多元线性回归详解2(求解过程)同这一章的梯度下降部分加起来,才是我们要讲的如何求解多元线性回归.如果写在一章中,内容过长,担心有的同学会看不完,所以拆分成两章.[坏笑]上一章中有提到利用解析解求解多元线性回归,虽然看起来很方便,但是在解析解求解的过程中会涉及到矩阵求逆的步骤.随着维度的增多,矩阵求逆的代价会越来越大(时间/空间),而且有…

    2022年9月11日
    2
  • 思科自研芯片_新思科技是大公司吗

    思科自研芯片_新思科技是大公司吗https://www.toutiao.com/a6673484789430878728/3月15日,上海,由智东西主办、AWE和极果联合主办的GTIC2019全球AI芯片创新峰会成功举办!峰会现场延续上一届的火爆场景,全场从开幕到下午结束座无虚席,而且有不少热情观众坚持站着听完峰会全程。20位海内外AI芯片业界大咖齐聚一堂,围绕AI芯片在架构创新、生态构建、场景…

    2025年8月26日
    5
  • fscanf()函数具体解释

    fscanf()函数具体解释

    2021年12月15日
    84
  • RPC接口设计_java rpc项目

    RPC接口设计_java rpc项目写在前边分布式架构是互联网应用的基础架构,很多新人入职以来就开始负责编写和调用阿里的各种远程接口。但如同结婚一般,用对一个正确的接口就如同嫁一个正确的人一样,往往难以那么顺利的实现,或多或少大家都会在这个上边吃亏。每年双十一系统调用复盘的时候,我都会听到以下声音你们调我的接口报错了竟然不会自己重试?我的返回值应该从这里取我返回isSuccess()==true,不代表业务成功,你…

    2022年10月13日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号