IOS swift开发——获取设备定位信息

IOS swift开发——获取设备定位信息,第1张

作为GIS开发人员,学习任何Android或者swift开发语言,可能第一时间想到的就是获取设备的定位信息。这里就来简述一下,我使用swift获取IOS定位信息的过程。

目录 添加后台定位能力模拟器定位模拟设置添加获取定位权限时的描述代码实现定位定位效果

添加后台定位能力

在项目配置里Singing&Capabilities中点击+Capability,在d出的窗口中选择Background Modes。选择后,下面会出现一个Background Modes菜单,然后勾选Location updates即可。

模拟器定位模拟设置

点击菜单栏的Features》Location,可以选择位置模拟的随机方式。

添加获取定位权限时的描述
  <key>NSLocationAlwaysUsageDescriptionkey>
	<string>允许用户后台定位string>
	<key>NSLocationWhenInUseUsageDescriptionkey>
	<string>使用您当前的位置信息string>
	<key>NSLocationAlwaysAndWhenInUseUsageDescriptionkey>
	<string>允许长期使用您的位置信息string>

info.plist文件中需要添加三项key值,具体可以参考这里

代码实现定位

定位功能主要是使用CoreLocation模块实现,定位服务管理类CLLocationManager的desiredAccuracy属性表示精准度,有如下6种选择:

kCLLocationAccuracyBestForNavigation :精度最高,一般用于导航kCLLocationAccuracyBest : 精确度最佳kCLLocationAccuracyNearestTenMeters :精确度10m以内kCLLocationAccuracyHundredMeters :精确度100m以内kCLLocationAccuracyKilometer :精确度1000m以内kCLLocationAccuracyThreeKilometers :精确度3000m以内
import UIKit
import CoreLocation


class ViewController: UIViewController ,CLLocationManagerDelegate{
    //定位管理器
    let locationManager:CLLocationManager = CLLocationManager()
    @IBOutlet weak var img: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        //设置定位服务管理器代理
        locationManager.delegate = self
        //设置定位进度
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        //更新距离
        locationManager.distanceFilter = 1
        发送授权申请
        locationManager.requestAlwaysAuthorization()
        locationManager.allowsBackgroundLocationUpdates=true
        // 进入后台后不停止
        locationManager.pausesLocationUpdatesAutomatically = false
        print("视图加载")
        if (CLLocationManager.locationServicesEnabled())
        {
            //允许使用定位服务的话,开启定位服务更新
            //                    locationManager.startUpdatingLocation()
            print("可以定位")
            startRequestLocation()
        }
        
    }
    
    @IBAction func test2(_ sender: Any) {
        print("121212")
    }
    // 开始尝试获取定位
    public func startRequestLocation() {
        if (self.locationManager != nil) && (CLLocationManager.authorizationStatus() == .denied) {
            // 没有获取到权限,再次请求授权
            print("拒绝授权")
            self.locationManager.requestWhenInUseAuthorization()
        } else {
            print("开始定位")
            locationManager.startUpdatingLocation()
        }
    }
    //定位改变执行,可以得到新位置、旧位置
    public  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //获取最新的坐标
        print("获取定位结果")
        let currLocation:CLLocation = locations.last!
        print("获取定位结果")
        print("经度:\(currLocation.coordinate.longitude)\n经度:\(currLocation.coordinate.longitude)\n海拔:\(currLocation.altitude)\n水平精度:\(currLocation.horizontalAccuracy)\n垂直精度:\(currLocation.verticalAccuracy)\n方向:\(currLocation.course)\n速度:\(currLocation.speed)")
    }
    // 代理方法,当定位授权更新时回调
    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        print("授权变化")
        // CLAuthorizationStatus
        // .notDetermined   用户还没有选择授权
        // .restricted   应用没有授权用户定位
        // .denied 用户禁止定位
        // .authorizedAlways 用户授权一直可以获取定位
        // .authorizedWhenInUse 用户授权使用期间获取定位
        // TODO...
        if status == .notDetermined {
            //未授予
        } else if (status == .restricted) {
            // 受限制,尝试提示然后进入设置页面进行处理
            
        } else if (status == .denied) {
            // 被拒绝,尝试提示然后进入设置页面进行处理
            
        }else{
            startRequestLocation()
        }
    }
    
    // 当获取定位出错时调用
    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        // 这里应该停止调用api
        print(error)
        print(error.localizedDescription)
        print("定位失败")
        self.locationManager.stopUpdatingLocation()
    }
}
定位效果

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/993720.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存