本文比较简单,只是获取到当前的位置信息...
在需要定位的控制器 .m 里面,添加如下代码:
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic,strong) CLLocationManager *manager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// do anythings you want to do...
[self getCurrentLocation];
}
- (void)getCurrentLocation {
// locationServicesEnabled这个是判断当前设备的定位服务是否可用
if(![CLLocationManager locationServicesEnabled]){
NSLog(@"bu ke yong");
return;
}
NSLog(@"ke yong");
// CLLocationManager这个类是用来定位的
self.manager = [[CLLocationManager alloc]init];
// 间隔多少米去重新定位
self.manager.distanceFilter =10;
// 这个属性是设计定位的精确度
// kCLLocationAccuracyBest这个是最好的精确度
self.manager.desiredAccuracy = kCLLocationAccuracyBest;
// 设置代理
self.manager.delegate = self;
// 如果当前设备大于等于8.0做一下特殊设置
if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0)
{
[self.manager requestAlwaysAuthorization];
// [manager requestWhenInUseAuthorization];
}
if ([[UIDevice currentDevice].systemVersion floatValue]>=9.0)
{
[self.manager allowsBackgroundLocationUpdates];//允许后台定位更新
}
// 开始定位
[self.manager startUpdatingLocation];
}
//这个代理方法是在定位失败的时候会调用
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(nonnull NSError *)error{
NSLog(@"==error===>>>%@",error.localizedDescription);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations{
CLLocation *location = [locations lastObject];
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
// CLPlacemark这个类里面装的是你当前定位到的那个地点的信息
CLPlacemark *mark = [placemarks firstObject];
// mark.country
// mark.location.coordinate
// 看到输出之后,我想你什么都明白了吧。。。
NSLog(@"======>>%@------%@=====>>>%@",mark.locality,mark.name,mark.addressDictionary);
}];
}
OK,到此结束...