首先要添加库CoreLocation.framework
然后需要在info.plist里添加两项NSLocationWhenInUseUsageDescription和NSLocationAlwaysUseUsageDescription后边的value随便写点就行
这是询问当前设备是否可以访问位置权限,
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interfaceViewController ()<CLLocationManagerDelegate>
@property (strong,nonatomic) CLLocationManager *locationManager;
@property (strong,nonatomic) UILabel *lab;
@property (strong,nonatomic) UILabel *lab2;
@end
@implementation ViewController
@synthesize lab,lab2;
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
lab = [[UILabelalloc] initWithFrame:CGRectMake(100, 100, 300, 50)];
lab.text = @"经度";
[self.viewaddSubview:lab];
lab2 = [[UILabelalloc] initWithFrame:CGRectMake(100, 200, 300, 50)];
lab2.text = @"纬度";
[self.viewaddSubview:lab2];
UIButton *btn = [[UIButtonalloc] initWithFrame:CGRectMake(150, 50, 100, 50)];
[btn setTitle:@"定位"forState:UIControlStateNormal];
[btn setTitleColor:[UIColorredColor] forState:UIControlStateNormal];
[btn addTarget:selfaction:@selector(Location:) forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:btn];
// 实例化
}
-(void) Location:(id) sender
{
// 判断是否可用定位服务
if ([CLLocationManagerlocationServicesEnabled]) {
NSLog(@"Star location");
//设置定位精度 最佳精度
// self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//设置距离过滤器为10米,表示每移动10米,更新一次数据
// self.locationManager.distanceFilter = 50;
self.locationManager = [[CLLocationManageralloc] init];
self.locationManager.delegate = self;
//访问是否可以定位 重点!!!!!!!!!!!!!!!!!!!搭配info.plist使用的,必须有
if ([self.locationManagerrespondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManagerrequestWhenInUseAuthorization];
[self.locationManagerrequestAlwaysAuthorization];
}
//开始监听位置
[self.locationManagerstartUpdatingLocation];
}
else
{
NSLog(@"UNSUPPORTED");
}
}
#pragma mark CLLocationManagerDelegate
-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray*)locations
{
NSLog(@"获取数据啊");
//获取最后一个定位数据
CLLocation *location = [locations lastObject];
//依次获取 经度,纬度,高度,速度,方向等
lab2.text = @"ddd";
lab.text = [NSStringstringWithFormat:@"%f",location.coordinate.longitude];
lab2.text = [NSStringstringWithFormat:@"%f",location.coordinate.latitude];
}
//实时更新数据
-(void) locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
// NSLog(@"获取数据啊");
}
-(void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"Failed");
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end