要利用CoreLocation,必须在frameworks里面加入“CoreLocation.framework”。
接着在info.plist文件中加入下面两个key,type为string类型,
value值自己定义,也可以不写,
NSLocationAlwaysUsageDescription
NSLocationWhenInUseUsageDescription
如图:
1. .h里导入
实现CLLocationManagerDelegate
#import
@interfaceHomeViewController :UIViewController
{
CLLocationManager*locationManager;
}
@property(strong,nonatomic)CLLocationManager*locationManager;
@end
2. .m里只需两个方法
//TODO:定位代理经纬度回调
- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation {
[locationManager stopUpdatingLocation];
NSLog(@"定位成功...");
NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]);
CLGeocoder* geoCoder = [[CLGeocoder alloc]init];
//根据经纬度反向地理编译出地址信息
[geoCoderreverseGeocodeLocation:newLocationcompletionHandler:^(NSArray*array,NSError*error){
if(array.count>0){
CLPlacemark*placemark = [array objectAtIndex:0];
//将获得的所有信息显示到导航栏上
_titleLab.text= [NSString stringWithFormat:@"%@%@",placemark.locality,placemark.subLocality];
//获取城市
NSString*city = placemark.locality;
if(!city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
NSLog(@"city = %@", city);
}
else if(error ==nil&& [array count] ==0)
{
NSLog(@"No results were returned.");
}
else if(error !=nil)
{
NSLog(@"An error occurred = %@", error);
}
}];
//系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
[manager stopUpdatingLocation];
}
//TODO:初始化定位管理器
- (void)initializeLocationService {
//初始化定位管理器
_locationManager= [[CLLocationManager alloc]init];
//设置代理
_locationManager.delegate=self;
//设置定位精确度到米
_locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//设置过滤器为无
_locationManager.distanceFilter=kCLDistanceFilterNone;
//开始定位
[_locationManager requestAlwaysAuthorization];//这句话ios8以上版本使用。
[_locationManager startUpdatingLocation];
}
最后不要忘了在viewDidLoad中初始化定位管理器
- (void)viewDidLoad {
[self initializeLocationService];
}
本人是用真机调试成功的.