标签:
在很多的APP开发中经常使用到定位功能,对于这种常用的方法很有必要对其封装使用
话不多说直接上代码:使用到了单例设计模式:
`
@protocol PositionToolDelegate <NSObject>
@optional
/**
@end
@interface PositionTool : NSObject<CLLocationManagerDelegate,PositionToolDelegate> {
CLLocationManager _locationManager;
NSMutableArray _locationArr ;
}
@property (nonatomic,assign) CLLocationDegrees latitude;//经度
@property (nonatomic,assign) CLLocationDegrees longtitude;//纬度
/**
//@property (nonatomic,strong) id<PositionToolDelegate> delegate;
/**
/**
@end.m方法的实现
if (_positionTool == nil) {
_positionTool=[[PositionTool alloc] init];
_positionTool.positionName=@"没有定位";
}
}(void)freeInfo {
if (_positionTool) {
_positionTool = nil;
}
}
(id)init {
self=[super init];
if (self) {
_locationArr=[[NSMutableArray alloc] init];
}
return self;
}
/**
/**
_locationManager=[[CLLocationManager alloc] init];
_locationManager.delegate=self;
//精度最高,耗电最大
_locationManager.desiredAccuracy=kCLLocationAccuracyBest;
_locationManager.distanceFilter = 200;
[_locationManager startUpdatingLocation];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >=8.0) {
[_locationManager requestAlwaysAuthorization];
}
}(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
switch (status) {
case kCLAuthorizationStatusNotDetermined:
if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[_locationManager requestAlwaysAuthorization];
}
break;
default:
break;
}
}
//获取经纬度
(void)locationManager:(CLLocationManager )manager didUpdateLocations:(NSArray<CLLocation > )locations {
CLLocation newLocation=locations[0];
//CLLocationCoordinate2D oldCoordinate=newLocation.coordinate;
//NSLog(@"旧的经度:%f,旧的纬度:%f",oldCoordinate.longitude,oldCoordinate.latitude);
//NSLog(@"新的经度:%f,新的纬度:%f",newLocation.coordinate.longitude,newLocation.coordinate.latitude);
self.latitude=newLocation.coordinate.latitude;
self.longtitude=newLocation.coordinate.longitude;
[manager stopUpdatingLocation];
CLGeocoder geocoder=[[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark > _Nullable placemarks, NSError _Nullable error) {
for (CLPlacemark *place in placemarks) {
self.positionName=place.name;
self.city=place.locality;
self.area=place.subLocality;
NSLog(@"%@",self.area);
}
for (id<PositionToolDelegate>delegate in _locationArr) {
if (delegate && [delegate respondsToSelector:@selector(noticePositionChanged)]) {
[delegate noticePositionChanged];
}
}
}];
for (id<PositionToolDelegate> delegate in _locationArr) {
if (delegate && [delegate respondsToSelector:@selector(noticePositionChanged)]) {
[delegate noticePositionChanged];
}
}
}
-(void)locationManager:(CLLocationManager )manager didUpdateToLocation:(CLLocation )newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"aaa%@", @"ok");
}
`
使用时候直接在使用到的地方加入
[[PositionTool shareInfo] getLocation];
标签:
原文地址:http://www.cnblogs.com/dengniqukanhai/p/5632546.html