单例继承自NSObject 很好的运用单例对开发有很大的帮助。
.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "JSONKit.h"
typedef void (^locationCompletion) (CLLocationCoordinate2D coor,NSString *city);
@interface XRLocationCenter : NSObject<CLLocationManagerDelegate>
{
CLLocationManager *_locationManager;
locationCompletion _completion;
BOOL _isNeedCity;
}
+(XRLocationCenter *)shared;
-(void)startLocationIsNeedCity: (BOOL)isNeedCity WithCompletion: (locationCompletion)completion;
@end
.m
static XRLocationCenter *_center = nil;
@implementation XRLocationCenter
+(XRLocationCenter *)shared
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_center = [[XRLocationCenter alloc] init];
});
return _center;
}
-(void)startLocationIsNeedCity: (BOOL)isNeedCity WithCompletion: (locationCompletion)completion
{
_completion = completion;
_isNeedCity = isNeedCity;
/**判断 是否开启定位模式*/
if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
/**创建一个location管理器*/
_locationManager = [[CLLocationManager alloc] init];
/**设置代理,实现定位成功或失败后执行相应地方法*/
_locationManager.delegate = self;
/**设置定位精度,有好几个等级,如果对精确度要求不是太高,可以设置10米或百米*/
_locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
/**设置距离过滤,当我超出上次定位多少米之后才重新定位*/
_locationManager.distanceFilter = 10;
/**当当前系统版本大于8.0的时候,执行以下方法*/
if ([UIDevice currentDevice].systemVersion.floatValue >8.0) {
/**ios8新加的,当使用的时候获取地理位置*/
[_locationManager requestAlwaysAuthorization];
}
/**发送请求*/
[_locationManager startUpdatingLocation];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请到系统设置里修改本应用的定位功能" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
[alertView show];
}
}
/**返回定位信息*/
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
/**停止更新定位信息*/
[_locationManager stopUpdatingLocation];
CLLocation *location = [locations firstObject];
if (_isNeedCity) {
/**进行反向地理解析,解析地址得到城市信息*/
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:[locations firstObject] completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *mark = [placemarks firstObject];
_completion(location.coordinate,mark.locality);
}];
}
else
{
_completion(location.coordinate,nil);
}
}
/**返回错误信息*/
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"%@",error);
}