您的位置:首页 > 其它

定位功能---封装的一个获取当前位置的经纬度信息的类

2015-10-13 20:12 633 查看
声明部分LocationManager.h

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

//声明这个block
typedef void(^GetLocationInformation)(CLLocation *location);

//定位管理
@interface LocationManager : NSObject <CLLocationManagerDelegate> {
}

@property (nonatomic, strong) CLLocationManager *manager;
//定义一个返回定位信息的block
@property (nonatomic, copy) GetLocationInformation callback;

//初始化管理器
+ (LocationManager *)shareSingleton;
//获取用户定位信息
+ (void)getUserLocation:(GetLocationInformation)block;

@end


实现部分LocationManager.m

#import "LocationManager.h"

//单例所指向的内存区域,整个App进程只有一次初始化
static LocationManager *manager = nil;

@implementation LocationManager

+ (LocationManager *)shareSingleton {
@synchronized (self) {
if (!manager) {
manager = [[LocationManager alloc] init];
}
}
return manager;
}

- (id)init {
self = [super init];
if (self) {
//系统的定位管理器
self.manager = [[CLLocationManager alloc] init];
self.manager.delegate = self;
//定位精度
self.manager.desiredAccuracy = kCLLocationAccuracyBest;
//请求授权
[self.manager requestAlwaysAuthorization];
}
return self;
}

/*
针对系统定位的顶层封装的好处
1.子视图控制器或其他组件可以用更少的代码完成相应的工作。
2.底层内容或者调用改变,只需改变中间的封装层。对于各个组件并无影响。
[LocationManager getUserLocation:^(CLLocation *location) {

}];
*/
+ (void)getUserLocation:(GetLocationInformation)block {
if (!manager) {
manager = [LocationManager shareSingleton];
}
manager.callback = block;
[manager.manager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
_callback([locations lastObject]);
[manager stopUpdatingLocation];
}

@end


调用

//经纬度
NSString *longitude;
NSString *latitude;
//获取用户当前的经纬度
[LocationManager getUserLocation:^(CLLocation *location) {
//拿到经纬度就可以去拼接参数拿数据了
longitude = [NSString stringWithFormat:@"%lf", location.coordinate.longitude];
latitude = [NSString stringWithFormat:@"%lf", location.coordinate.latitude];
}];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: