先導入 然後在 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); }];