获取定位信息
程序员文章站
2022-03-08 22:43:16
先导入 然后在 info.plist 文件中添加 Privacy - Location Always and When In Use Usage Description 和 Privacy - Location When In Use Usage Description 两个就可以了。 Locati ......
先导入
然后在 info.plist 文件中添加 Privacy - Location Always and When In Use Usage Description 和 Privacy - Location When In Use Usage Description 两个就可以了。
LocationManager.h
#import <Foundation/Foundation.h> typedef void(^LocationBlock)(NSString *lat, NSString *lon); @interface LocationManager : NSObject + (instancetype)shareManager; - (void)getGps:(LocationBlock)block; @property (nonatomic, copy) NSString *lat; @property (nonatomic, copy) NSString *lon; @end
LocationManager.m
#import "LocationManager.h" #import <CoreLocation/CoreLocation.h> @interface LocationManager ()<CLLocationManagerDelegate> @property (nonatomic, strong) CLLocationManager *locManager; @property (nonatomic, copy) LocationBlock block; @end @implementation LocationManager + (instancetype)shareManager { static LocationManager *_manager; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _manager = [[LocationManager alloc] init]; }); return _manager; } - (instancetype)init { if (self = [super init]) { _locManager = [[CLLocationManager alloc] init]; // 精确度 [_locManager setDesiredAccuracy:kCLLocationAccuracyBest]; // 精确到米 _locManager.distanceFilter = 100; _locManager.delegate = self; if (![CLLocationManager locationServicesEnabled]) { // 判断当前服务是否开启 NSLog(@"开启定位服务"); } else { // 当前状态 CLAuthorizationStatus status = [CLLocationManager authorizationStatus]; if (status == kCLAuthorizationStatusNotDetermined) { // 未选中状态时候 [_locManager requestWhenInUseAuthorization]; } } } return self; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { CLLocationCoordinate2D coor = newLocation.coordinate; NSString *lat = [NSString stringWithFormat:@"%@", @(coor.latitude)]; NSString *lon = [NSString stringWithFormat:@"%@", @(coor.longitude)]; [LocationManager shareManager].lat = lat; [LocationManager shareManager].lon = lon; self.block(lat, lon); // 停止定位 [self.locManager stopUpdatingLocation]; } - (void)getGps:(LocationBlock)block { self.block = block; // 开始定位 [self.locManager startUpdatingLocation]; } @end
调用方法:
[[LocationManager shareManager] getGps:^(NSString *lat, NSString *lon) { NSLog(@"%@, %@", lat, lon); }];
上一篇: 小红书如何查看我的收益?