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

原文地址:https://www.cnblogs.com/tangranyang/p/4655614.html