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)
上一篇 2022年7月26日 下午7:00
下一篇 2022年7月26日 下午7:00


相关推荐

  • pycharm基础使用方法

    pycharm基础使用方法nbsp 0 前言 nbsp Pycharm nbsp 作为一款针对 nbsp Python nbsp 的编辑器 配置简单 功能强大 使用起来省时省心 对初学者友好 这也是为什么编程教室一直推荐新手使用 nbsp Pycharm nbsp 的原因 本文我们将介绍 nbsp pycharm nbsp 编辑器的基本使用方法 主要包括以下几个方面 下载安装 新建项目流程 配置 nbsp Pycharm Python 控制台 其他参考资料

    2026年3月27日
    1
  • 数域相关概念「建议收藏」

    数域相关概念「建议收藏」现在开始密码学的学习阶段了,数学知识是必不可少的。数环:定义:设S是复数集的非空子集。如果S中的数对任意两个数的和、差、积(没有商)仍属于S,则称S是一个数环。例如整数集Z就是一个数环,有理数集Q、实数集R、复数集C等都是数环。性质:1.任何数环都包含数零(即零环是最小的数环)。2.设S是一个数环。若a∈S,则na∈S(n∈Z)。3.若M

    2025年7月12日
    6
  • c# savefiledialog_game是什么意思中文

    c# savefiledialog_game是什么意思中文1、这里通过一个例子来讲解saveFileDialog的使用方法,首先创建一个小的winform程序,然后在主界面中放入一个按钮、一个textbox,按钮用来弹出saveFileDialog,然后textbox用来接收saveFileDialog选择之后的文件路径,如下图:2、下图中的代码就是程序的全部代码了,对其中重要的代码进行解释:InitialDirectory方法:设置save…

    2026年4月13日
    6
  • 旧手机别扔!装个OpenClaw,立刻变成实用AI机器人

    旧手机别扔!装个OpenClaw,立刻变成实用AI机器人

    2026年3月12日
    2
  • 激光雷达和超声波雷达区别_雷达是超声波还是电磁波

    激光雷达和超声波雷达区别_雷达是超声波还是电磁波转自:http://www.sohu.com/a/201826967_524185不知何时,自动驾驶技术从电影中跳出来,直接被拉到人们视野中。不过,去年特斯拉却因为几起自动驾驶事故,官网不得不把自动驾驶字眼改为辅助驾驶。本期《汽车总动员》讨论的不是自动驾驶,而是被称为自动驾驶汽车“眼睛”的雷达。目前主流的“眼睛”有四类——毫米波雷达、激光雷达、超声波雷达、摄像头。他们各自都有自己的特点,比如摄像头…

    2025年10月31日
    4
  • Asp.Net Core-几行代码解决Razor中的嵌套if语句

    Asp.Net Core-几行代码解决Razor中的嵌套if语句

    2021年9月15日
    55

发表回复

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

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