Here is the code to get the user's current location using the block
1) #import <CoreLocation/CoreLocation.h>
2) <CLLocationManagerDelegate>
3) in the .h file
//Location typedef void(^locationBlock)(); //Location -(void)GetCurrentLocation_WithBlock:(void(^)())block; @property (nonatomic, strong) locationBlock _locationBlock; @property (nonatomic,copy)CLLocationManager *locationManager; @property (nonatomic)CLLocationCoordinate2D coordinate; @property (nonatomic,strong) NSString *current_Lat; @property (nonatomic,strong) NSString *current_Long;
4) in the .m file
#pragma mark - CLLocationManager -(void)GetCurrentLocation_WithBlock:(void(^)())block { self._locationBlock = block; _locationManager = [[CLLocationManager alloc] init]; [_locationManager setDelegate:self]; [_locationManager setDistanceFilter:kCLDistanceFilterNone]; [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; if (IS_OS_8_OR_LATER) { if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [_locationManager requestWhenInUseAuthorization]; [_locationManager requestAlwaysAuthorization]; } } [_locationManager startUpdatingLocation]; } - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { CLLocation *currentLoc=[locations objectAtIndex:0]; _coordinate=currentLoc.coordinate; _current_Lat = [NSString stringWithFormat:@"%f",currentLoc.coordinate.latitude]; _current_Long = [NSString stringWithFormat:@"%f",currentLoc.coordinate.longitude]; NSLog(@"here lat %@ and here long %@",_current_Lat,_current_Long); self._locationBlock(); [_locationManager stopUpdatingLocation]; _locationManager = nil; } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { }
5) Call function
- (void)viewDidLoad { [super viewDidLoad]; [self GetCurrentLocation_WithBlock:^{ NSLog(@"Lat ::%f,Long ::%f",[self.current_Lat floatValue],[self.current_Long floatValue]); }]; }
6) And add the line below to .plist
In the Info.plist file, you must add either or both of the keys listed below.
NSLocationWhenInUseUsageDescription NSLocationAlwaysUsageDescription
Hardik.t
source share