Core Location是iOS SDK中一个提供设备位置的框架。可以使用三种技术来获取位置:GPS、蜂窝或WiFi。在这些技术中,GPS最为精准,如果有GPS硬件,Core Location将优先使用它。如果设备没有GPS硬件(如WiFi iPad)或使用GPS获取当前位置时失败,Core Location将退而求其次,选择使用蜂窝或WiFi。
Core Location的大多数功能是由位置管理器(CLLocationManager)提供的,可以使用位置管理器来指定位置更新的频率和精度,以及开始和停止接收这些更新。
要使用位置管理器,必须首先将框架Core Location加入到项目中,再导入其接口文件:
#
import
<corelocation corelocation.h
>
_locationManager=[[CLLocationManager alloc]init];
if (![CLLocationManager locationServicesEnabled]) {
NSLog(@"定位服务当前可能尚未打开,请设置打开!");
return;
}
//如果没有授权则请求用户授权
[_locationManager requestAlwaysAuthorization];
[_locationManager requestWhenInUseAuthorization];
_locationManager.delegate = self;
//设置定位精度
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//定位频率,每隔多少米定位一次
CLLocationDistance distance = 100.0;//十米定位一次
_locationManager.distanceFilter = distance;
//启动跟踪定位
[_locationManager startUpdatingLocation];
_clickBtnBOOL = YES;
if ([CLLocationManager locationServicesEnabled] &&
([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized
|| [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
//定位功能可用,开始定位
[MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = @"定位中";
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
[_locationManager startUpdatingLocation];
}
else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
alert = [[UIAlertView alloc]initWithTitle:@"定位功能不可用" message:@"请到设置-隐私-定位服务打开" delegate:self cancelButtonTitle:@"设置" otherButtonTitles:@"取消", nil];
alert.delegate = self;
[alert show];
}
}
#pragma mark UIAlertViewDelegate 代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if( alert==alertView ){
if (buttonIndex == 0) {
[self exitApplication];
}
}
}
-(void)exitApplication{
//跳转手机上定位服务
NSURL*url=[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"];
[[UIApplication sharedApplication] openURL:url];
}
- (
void
)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//获得当前位置经纬度}
- (
void
)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"%@",error);}