zoukankan      html  css  js  c++  java
  • 1.CoreLocation 使用,获取当前位置

    1.

          ios7只要开始定位,系统就会自动要求你对应用程序授权

         ios8之后,必须要代码中实现要求用户对应用程序授权 ,在plist中添加以下两个属性

         NSLocationWhenInUseDescription,允许在前台获取GPS的描述

         NSLocationAlwaysUsageDescription,允许在后台获取GPS的描述

     

    2,代码

    #import "ViewController.h"

    #import <CoreLocation/CoreLocation.h>

     

    @interface ViewController ()<CLLocationManagerDelegate>

     

    @property(nonatomic,strong)CLLocationManager*manger;

     

    @end

     

    @implementation ViewController

     

    -(CLLocationManager*)manger

    {

        if (_manger==nil) {

            _manger=[[CLLocationManager alloc]init];

        }

        return _manger;

    } 

    - (void)viewDidLoad {

        [super viewDidLoad];

        

        self.manger.delegate=self;

        

        if ([[UIDevice currentDevice].systemVersion floatValue]>8.0) {

            [self.manger requestAlwaysAuthorization];//后台运行的时候执行获取位置信息

            //[self.manger requestWhenInUseAuthorization];//前台执行的时候获取位置信息

        }

        else

        {

            [self.manger startUpdatingLocation];

        }

    }

    //授权状态改变的时候调用

    -(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status

    {

        if (status == kCLAuthorizationStatusNotDetermined) {

            NSLog(@"等待用户授权");

        }else if (status == kCLAuthorizationStatusAuthorizedAlways ||

                  status == kCLAuthorizationStatusAuthorizedWhenInUse)

            

        {

            NSLog(@"授权成功");

            // 开始定位

            [self.manger startUpdatingLocation];

            

        }

        else

        {

            NSLog(@"授权失败");

        }

    }

     

    -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

    {

        //如果只需要获取一次,可以获取位置之后就停止

        [self.manger stopUpdatingLocation];

        CLLocation *location=[locations lastObject];

        NSLog(@"经度=%f,维度=%f   速度=%f  ",location.coordinate.latitude,location.coordinate.longitude,location.speed);

    }

     

     

     

     

     

     

     

    @end

  • 相关阅读:
    (九十三)蓝牙的基本使用
    (九十二)加速计的用法(过期方法+新方法)
    (九十一)距离传感器的使用
    1060. Are They Equal (25)
    (九十)使用多个storyboard+代码实现控制器的分开管理
    (八十九)用AutoLayout实现动画和Label根据内容自动调整
    HDU 2013:蟠桃记
    HDU 2050:折线分割平面
    HDU 2042:不容易系列之二
    HDU 1465:不容易系列之一
  • 原文地址:https://www.cnblogs.com/tangranyang/p/4655614.html
Copyright © 2011-2022 走看看