首先需要在info.plist中添加:
NSLocationAlwaysUsageDescription、NSLocationWhenInUseUsageDescription
都设置为Yes
Paste_Image.png
同时,导入CoreLocation.framework
在这里我新建了LocationManager的类
- LocationManager.h
#import <Foundation/Foundation.h>
@class CLLocation;
@protocol LocationManagerDelegate <NSObject>
/**
* 代理方法定位成功
*
* @param currentCity 获取当前的城市
* @param location CLLocation.coordinate可获取坐标
*/
-(void )LocationManagerWithCurrentCity:(NSString *)currentCity CLLocation:(CLLocation *)location;
/**
* 代理方法定位失败
*/
-(void)LocationManagerLocateFail;
@end
@interface LocationManager : NSObject
//单例
+(LocationManager *)sharedInstance;
// 开始定位
-(void)locate;
@property (nonatomic, weak) id <LocationManagerDelegate> delegate;
@end
- LocationManager.m
#import "LocationManager.h"
#import "CoreLocation/CoreLocation.h" //定位
@interface LocationManager ()<CLLocationManagerDelegate>
@property (nonatomic ,strong) CLLocationManager *locationManager;
@property (nonatomic ,copy ) NSString *currentCity;
@end
@implementation LocationManager
+(LocationManager *)sharedInstance{
static LocationManager *shareObj = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareObj = [[LocationManager alloc]init];
});
return shareObj;
}
-(instancetype)init{
if(self = [super init]){
self.locationManager = [[CLLocationManager alloc] init] ;
self.locationManager.delegate = self;
// 判断定位操作是否被允许
if([CLLocationManager locationServicesEnabled]) {
// self.locationManager.distanceFilter=1.0;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 10;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
[self.locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据(iOS8定位需要)
[self.locationManager requestWhenInUseAuthorization]; //使用中授权
}
}else {
//提示用户无法进行定位操作
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[alertView show];
}
}
return self;
}
#pragma mark - 定位
- (void)locate{
// 开始定位
[self.locationManager startUpdatingLocation];
}
//实现定位协议回调方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
//系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
[self.locationManager stopUpdatingLocation];
//此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
CLLocation *currentLocation = [locations lastObject];
//将经度显示到label上
XLog(@"%@",[NSString stringWithFormat:@"%lf", currentLocation.coordinate.longitude]) ;
//将纬度现实到label上
XLog(@"%@", [NSString stringWithFormat:@"%lf", currentLocation.coordinate.latitude]) ;
// 获取当前所在的城市名
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//根据经纬度反向地理编译出地址信息
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
{
if (array.count > 0)
{
CLPlacemark *placemark = [array objectAtIndex:0];
// NSLog(@"name,%@",place.name); // 位置名
// NSLog(@"thoroughfare,%@",place.thoroughfare); // 街道
// NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
// NSLog(@"locality,%@",place.locality); // 市
// NSLog(@"subLocality,%@",place.subLocality); // 区
// NSLog(@"country,%@",place.country); // 国家
NSString *city = placemark.locality;
if (!city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
NSString *currentCity = [city stringByReplacingOccurrencesOfString:@"市" withString:@""];
self.currentCity = currentCity;
if([self.delegate respondsToSelector:@selector(LocationManagerWithCurrentCity:CLLocation:)]){
[self.delegate LocationManagerWithCurrentCity:self.currentCity CLLocation:currentLocation];
}
}
else if (error == nil && [array count] == 0)
{
NSLog(@"No results were returned.");
}
else if (error != nil)
{
NSLog(@"An error occurred = %@", error);
}
}];
//系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
[manager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
// [MBProgressHUD showError:@"定位失败"];
if ([self.delegate respondsToSelector:@selector(LocationManagerLocateFail)]) {
[self.delegate LocationManagerLocateFail];
}
if (error.code == kCLErrorDenied) {
// 提示用户出错原因,可按住Option键点击 KCLErrorDenied的查看更多出错信息,可打印error.code值查找原因所在
}
}
@end