#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
//必须把CLLocationManger声明属性
@property (nonatomic, strong) CLLocationManager *mgr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1.初始化manager对象
self.mgr = [CLLocationManager new];
//2.询问/征求用户定义允许(iOS8+)
if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
//需要用户的同意(仅仅是在使用期间/前台)+Info.plist添加key
[self.mgr requestWhenInUseAuthorization];
//征求前台和后台都定位+Info.plist添加key
// [self.mgr requestAlwaysAuthorization];
} else {
//直接定位
[self.mgr startUpdatingLocation];
}
//3.设置代理
self.mgr.delegate = self;
}
//监听用户的状态(同意/不同意)
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
//用户同意前台定位; 开始定位(开始更新位置)
//系统默认每一秒发送一次请求(不能改)
//定位的精确度(默认精度是最高精度/耗电;其他的设置相对不耗电)
self.mgr.desiredAccuracy = kCLLocationAccuracyHundredMeters;
//位置的更新频率(减少didUpdateLocations方法的调用;模拟器没有什么用处)
self.mgr.distanceFilter = 10000;//单位:米
// [self.mgr startUpdatingLocation];
//V2:保证只发送一次请求(模拟器不靠谱)
[self.mgr requestLocation];
} else if (status == kCLAuthorizationStatusDenied) {
//用户没有同意定位
NSLog(@"用户不同意定位....");
}
}
//[self.mgr startUpdatingLocation];
//监听用户的位置触发下面的方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
//获取用户的最新位置(数组的最后一个对象)
CLLocation *location = [locations lastObject];
NSLog(@"纬度%f; 经度%f", location.coordinate.latitude, location.coordinate.longitude);
//调用停止定位服务(不会再触发这个方法)
[self.mgr stopUpdatingLocation];
//设置mgr为nil,一定只调用一次
// self.mgr = nil;//因为调用requestLocation方法
}
//失败获取用户的位置
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"服务器返回失败:%@", error);
}
@end
iOS中用CoreLocation实现定位
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1、首先得引入CoreLocation系统框架 2、导入头文件 遵循代理 import <CoreLocation...
- From http://developer.android.youdaxue.com/training/index...