有些时候可能只是用到地图的某些功能,比如获取当前所在的城市,然后根据城市返回相应的数据,而不需要其他操作,每次都要写那么几行代码,所以就做了小小的封装,后期可能会添加新功能,来适应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
时间: 2024-10-14 07:22:41