0

I am trying to get latitude & longitude. I am running following code on actual device but I always get zero for latitude & longitude. I also import library and set delegate also. May I know what is wrong and how to do? My device has ios 8.

CLLocationManager *locationManager = [[CLLocationManager alloc] init];

if ([locationManager locationServicesEnabled])
{
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
}


CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];

NSString *str=[[NSString alloc] initWithFormat:@" latitude:%f longitude:%f",coordinate.latitude,coordinate.longitude];
NSLog(@"%@",str);
Khant Thu Linn
  • 5,905
  • 7
  • 52
  • 120
  • 1
    Are delegate methods being called? you need to make some changes for iOS 8 as suggested here http://stackoverflow.com/questions/25844430/xcode-6-gm-cllocationmanager/25844674#25844674 – Bhumit Mehta Oct 21 '14 at 09:43
  • did you set debug to a location? – noobsmcgoobs Oct 21 '14 at 09:59
  • How to set debug to location? @noobsmcgoobs – Khant Thu Linn Oct 21 '14 at 11:11
  • My delegate are not called. I have put both NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription in my plist. When I call location, my app prompt user alert to allow or not. However, b4 I click, it automatically close. @Bhumit – Khant Thu Linn Oct 21 '14 at 11:11
  • before startUpatingLocation put this: if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [locationManager requestWhenInUseAuthorization]; } – TonyMkenu Oct 21 '14 at 11:14
  • 2) try to make locationManager a “Property": @property (strong, nonatomic) CLLocationManager *locationManager; – TonyMkenu Oct 21 '14 at 11:16
  • Thanks you all. now it is working. I need to call this two method and also set up as described by @Bhumit [[AppDelegate instance].locationManager requestWhenInUseAuthorization]; [[AppDelegate instance].locationManager startUpdatingLocation]; – Khant Thu Linn Oct 21 '14 at 11:30
  • 1
    Also beware, the simulator is buggy and gives random lat and long at times. I suspect this has something to do with the new OSX. – noobsmcgoobs Oct 21 '14 at 23:34

1 Answers1

2

you have to get the current location in delegate method

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *currentLocation = [locations objectAtIndex:0];
}
kabarga
  • 803
  • 6
  • 11