您的位置:首页 > 移动开发 > IOS开发

ios获取当前城市 ,位置,坐标,经纬度

2015-09-20 14:39 573 查看
有些时候可能只是用到地图的某些功能,比如获取当前所在的城市,然后根据城市返回相应的数据,而不需要其他操作,每次都要写那么几行代码,所以就做了小小的封装,后期可能会添加新功能,来适应app的各种需求(使其变得更为强大)

github打包地址:https://github.com/iOSSinger/SGLocation

核心代码:

使用方法:

//一行代码获取当前城市
[loc setGetCity:^(NSString *city) {
NSLog(@"%@",city);
}];

//一行代码获取当前位置
[loc setGetLocation:^(NSString *location) {
NSLog(@"%@",location);
}];

//一行代码获取当前坐标
[loc setGetCoordinate:^(CLLocationCoordinate2D coodinate) {
NSLog(@"%f-%f",coodinate.latitude,coodinate.longitude);
}];


具体实现代码,其实用block将值传回来,而不需要使用代理

#import "SGLocation.h"

@interface SGLocation()<CLLocationManagerDelegate>

@property (nonatomic,strong) CLLocationManager *manager;

@end

@implementation SGLocation

static SGLocation *_instance;
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}

+ (instancetype)shareLocation{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}

- (CLLocationManager *)manager{
if (_manager == nil) {
_manager = [[CLLocationManager alloc] init];
_manager.delegate = self;
[_manager requestWhenInUseAuthorization];
}
return _manager;
}
- (void)setGetCity:(void (^)(NSString *))getCity{
_getCity = getCity;
[self.manager startUpdatingLocation];
}
- (void)setGetCoordinate:(void (^)(CLLocationCoordinate2D))getCoordinate{
_getCoordinate = getCoordinate;
[self.manager startUpdatingLocation];
}
- (void)setGetLocation:(void (^)(NSString *))getLocation{
_getLocation = getLocation;
[self.manager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *loc =[locations lastObject];

//反地理编码
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray *placemarks, NSError *error) {
if (placemarks.count) {
//获取当前城市
CLPlacemark *mark = placemarks.firstObject;
NSDictionary *dict = [mark addressDictionary];
NSString *city = [dict objectForKey:@"State"];
//城市
if (self.getCity) {
self.getCity(city);
[self.manager stopUpdatingLocation];
}

//坐标
if(self.getCoordinate){
self.getCoordinate(mark.location.coordinate);
[self.manager stopUpdatingLocation];
}

//位置信息
if (self.getLocation) {
self.getLocation(mark.name);
[self.manager stopUpdatingLocation];
}
}
}];
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: