创建调用方法,在.h文件里
#import <Foundation/Foundation.h> @interface RMMapLocation : NSObject { void (^saveGpsCallBack)(double lattitude,double longitude); } + (void)getGps:(void(^)(double lattitude,double longitude))block; + (void)stop;
在.m文件里进行方法的实现
#import "RMMapLocation.h" @interface RMMapLocation ()<CLLocationManagerDelegate> @property (strong, nonatomic)CLLocationManager *locManager; @end @implementation RMMapLocation + (instancetype)sharedGpsManager { static id mapLocation; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (!mapLocation) { mapLocation = [[RMMapLocation alloc] init]; } }); return mapLocation; } - (instancetype)init { self = [super init]; if (self) { [self getCurrentLocation]; } return self; } - (void)getCurrentLocation { self.locManager = [[CLLocationManager alloc] init]; self.locManager.delegate = self; self.locManager.desiredAccuracy = kCLLocationAccuracyBest; self.locManager.distanceFilter = 10.0; } - (void)getGps:(void (^)(double lat, double lng))gps { if ([CLLocationManager locationServicesEnabled] == FALSE) { return; } saveGpsCallBack = [gps copy]; [self.locManager startUpdatingLocation]; } + (void)getGps:(void (^)(double, double))block { [[RMMapLocation sharedGpsManager] getGps:block]; } - (void)stop { [self.locManager stopUpdatingLocation]; } + (void)stop { [[RMMapLocation sharedGpsManager] stop]; } #pragma mark - locationManagerDelegate - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { RMLog(@"%f,%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude); double latitude = newLocation.coordinate.latitude; double longitude = newLocation.coordinate.longitude; if (saveGpsCallBack) { saveGpsCallBack(latitude,longitude); } } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { RMLog(@"%@",error); // [RMUtils showMessage:@"定位失败"]; }
在须要调用的文件里引入头文件后调用方法的实现(如需仅仅定位一次,则调用stop方法就可以)
[RMMapLocation getGps:^(double lattitude, double longitude) { RMLog(@"%f---%f",lattitude,longitude); }];
demo地址:http://download.csdn.net/detail/sinat_28585351/9491130
https://github.com/Raymon-lau/CLLocationManager