iOS9定位获取经纬度 swift

定位服务是不少程序中都用到的,主要使用CoreLocation库中的CLLocationManager类和CLLocation类。git

实现结果使用弹窗显示,以下图:异步

实现步骤:async

首先,咱们须要在Info.plist文件中添加两个字段:ide

//始终开启定位的用户提示信息NSLocationAlwaysUsageDescription//仅在程序使用时开启定位的用户提示信息NSLocationWhenInUseUsageDescription

以下图,Value为自定义信息,用来显示在系统的设置界面中:ui

当程序打开时,若是用户没有选择过是否容许App获取定位信息,会弹出窗口显示,在窗口中会显示NSLocationWhenInUseUsageDescription的内容:spa

在系统的设置-定位中,显示以下(应用程序说明):线程

如今,能够开始写代码了:代理

import UIKitimport CoreLocationclass ViewController: UIViewController,CLLocationManagerDelegate {

    var locationManager:CLLocationManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //若是设备没有开启定位服务
        if !CLLocationManager.locationServicesEnabled(){
            dispatch_async(dispatch_get_main_queue()){
                SCMessageBox.showquick(self, contentMsg: "没法定位,由于您的设备没有启用定位服务,请到设置中启用")
            }
            return
        }
        
        locationManager = CLLocationManager()
        
        //设置精确度
        locationManager.desiredAccuracy = kCLLocationAccuracyBest        //变化距离  超过50米 从新定位
        locationManager.distanceFilter = 50
        //在IOS8以上系统中,须要使用requestWhenInUseAuthorization方法才能弹窗让用户确认是否容许使用定位服务的窗口
        if SCDevice.getVersion() >=  8.0 {
        
            //状态为,用户尚未作出选择,那么就弹窗让用户选择
            if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined {
                locationManager.requestWhenInUseAuthorization()
                //locationManager.requestAlwaysAuthorization()
            }
            //状态为,用户在设置-定位中选择了【永不】,就是不容许App使用定位服务
            else if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Denied){
                //须要把弹窗放在主线程才能强制显示
                dispatch_async(dispatch_get_main_queue()){
                    SCMessageBox.showquick(self, contentMsg: "没法定位,由于您没有受权本程序使用定位,请至设置中开启!")
                    return
                }
            }
        }
        //设置定位获取成功或者失败后的代理,Class后面要加上CLLocationManagerDelegate协议
        locationManager.delegate = self        
        //开始获取定位信息,异步方式
        locationManager.startUpdatingLocation()
    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        SCMessageBox.showquick(self, contentMsg: "定位发生异常:\(error)")
    }
    
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        if locations.count > 0{ //  使用last 获取 最后一个最新的位置, 前面是上一次的位置信息
            var locationInfo:CLLocation = locations.last as! CLLocation
            SCMessageBox.showquick(self, contentMsg: "经度:\(locationInfo.coordinate.longitude),纬度:\(locationInfo.coordinate.latitude)")
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }}
相关文章
相关标签/搜索