How can I get the current position on iOS?

advertisements

This question already has an answer here:

  • how to get the current location position in map on iphone 2 answers

I can't get current location. When I launch my app in different place, App can get last location. But I don't want to last location. If you close the app and restart it, now app can get current location. How can I get current location even if it is first launch of application?

- (void)viewDidLoad
{
    [super viewDidLoad];

    [locationManager startUpdatingLocation];

    self.mapView.delegate = self;
    [self.mapView setShowsUserLocation:YES];

    locationManager.delegate=self;

    locationManager = [[CLLocationManager alloc] init];

    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    locationManager.distanceFilter=kCLDistanceFilterNone;

    location = [locationManager location];

    CLLocationCoordinate2D coord;
    coord.longitude = location.coordinate.longitude;
    coord.latitude = location.coordinate.latitude;
    lat = coord.latitude;
    longt = coord.longitude;
}


You are doing [locationManager startUpdatingLocation]; before setting its delegate

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;

[locationManager startUpdatingLocation];

And implement its delegate method

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{

}