兼容iOS 8.0以上获取地理位置信息
仅仅是个记录直接上代码 ~
.h 文件
1 2 3 4 5 6 7 8 9 | typedef void(^GetLatitudeAndLongitude)(NSString *lat,NSString *lng); @interface LocationManger : NSObject @property (nonatomic, strong) NSDictionary * locationDict; + (instancetype)sharedLoaction; - (void)getGps:(GetLatitudeAndLongitude)block; |
.m 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | @interface LocationManger ()<CLLocationManagerDelegate> { GetLatitudeAndLongitude block; } @property (nonatomic, strong) CLLocationManager * locManager; @end @implementation LocationManger +(instancetype)sharedLoaction { static LocationManger *standard = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ standard = [[LocationManger alloc]init]; }); return standard; } - (instancetype)init { self = [super init]; if (self) { _locManager = [[CLLocationManager alloc] init]; [_locManager setDesiredAccuracy:kCLLocationAccuracyBest]; [_locManager setDelegate:self]; if([_locManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { [_locManager requestAlwaysAuthorization]; // 永久授权 } _locManager.distanceFilter=100; } return self; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { CLLocationCoordinate2D loc = [newLocation coordinate]; NSString * lat = [NSString stringWithFormat:@"%f",loc.latitude];//get latitude NSString *lon = [NSString stringWithFormat:@"%f",loc.longitude];//get longitude if (lat!=nil && lon!=nil) { self.locationDict = @{@"lat":lat, @"lng":lon}; block(lat,lon); [manager stopUpdatingLocation]; } } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { if ([error code] == kCLErrorDenied) { //访问被拒绝 } if ([error code] == kCLErrorLocationUnknown) { //无法获取位置信息 } } - (void)getGps:(GetLatitudeAndLongitude)myblock { block = myblock; if ([CLLocationManager locationServicesEnabled] == FALSE) { return; } [_locManager startUpdatingLocation]; } @end |
还要在info.plist文件里创建NSLocationAlwaysUsageDescription
这一项,对应的值不能乱写,它会在询问是否允许定位中显示出来,这样写 ~ 比如我们需要获取您的地理位置
。
这么调用 ~
1 2 | [[LocationManger sharedLoaction] getGps:^(NSString *lat, NSString *lng) {
}];
|