iOS8中使用CoreLocation定位
1.引入CoreLocation.framework 添加委托CLLocationManagerDelegate
2.
{
float Currentlat,Currentlon;
CLLocationManager *locationManager;
UILabel *cityLabel;
}
3.viewDidLoad里添加
if ([CLLocationManager locationServicesEnabled] == NO) {
NSLog(@"没有GPS服务");
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"警告" message:@"没有GPS服务" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
[alertView show];
}else{
CLLocationManager *locmanager = [[CLLocationManager alloc]init];//先定义一个cllocationmanager的实例
locationManager=locmanager;
[locationManager requestAlwaysAuthorization];//相对应info.plist中的NSLocationAlwaysUsageDescription键
[locmanager setDelegate:self]; //设置代理为本身
[locmanager setDesiredAccuracy:kCLLocationAccuracyBest];//设置精确度为最准确
locmanager.distanceFilter = 1000.0f;
[locationManager startUpdatingLocation];
}
4.
//ios6.0以上
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *newLocation = [locations lastObject];
CLLocationCoordinate2D coor = newLocation.coordinate;
Currentlat = coor.latitude;
Currentlon = coor.longitude;
NSLog(@"当前维度ios7 %f 当前经度 %f",Currentlat,Currentlon);
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark * placemark in placemarks) {
NSDictionary *test = [placemark addressDictionary];
// Country(国家) State(城市) SubLocality(区)
cityLabel.text=[test objectForKey:@"State"];
}
}];
[manager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(@"定位失败");
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"定位失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alert show];
}
5.
ios8必须注意:
iOS8对定位进行了一些修改,其中包括定位授权的方法,CLLocationManager增加了下面的两个方法:
(1)始终允许访问位置信息
- (void)requestAlwaysAuthorization;
(2)使用应用程序期间允许访问位置数据
- (void)requestWhenInUseAuthorization;
在运行开始更新前加下面这句
[locationManager requestAlwaysAuthorization];//相对应info.plist中的NSLocationAlwaysUsageDescription键
2、在Info.plist文件中添加如下配置:
(1)NSLocationAlwaysUsageDescription
(2)NSLocationWhenInUseUsageDescription
这两个键的值就是授权alert的描述,示例配置如下[勾选Show Raw Keys/Values后进行添加
]:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。