Last Updated: December 26, 2018
·
11.27K
· novalagung

iOS - get current location information

Here the steps how to get current location information in iOS dev.

First, you need to add CoreLocation library to your project.

Next, import <CoreLocation/CoreLocation.h> and use CLLocationManagerDelegate

Define 3 variables below :

CLLocationManager *locationManager;
CLGeocoder *geocoder;
int locationFetchCounter;

instantiate those variables in viewDidLoad :

- (void)viewDidLoad {
    [super viewDidLoad];
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    geocoder = [[CLGeocoder alloc] init];
}

// execute this method to start fetching location
- (IBAction)doFetchCurrentLocation:(id)sender {
    locationFetchCounter = 0;

    // fetching current location start from here
    [locationManager startUpdatingLocation];
}

implements locationManager:didUpdateLocations and locationManager:didFailWithError for handling [locationManager startUpdatingLocation]'s result.

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    // this delegate method is constantly invoked every some miliseconds.
    // we only need to receive the first response, so we skip the others.
    if (locationFetchCounter > 0) return;
    locationFetchCounter++; 

    // after we have current coordinates, we use this method to fetch the information data of fetched coordinate
    [geocoder reverseGeocodeLocation:[locations lastObject] completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks lastObject];

        NSString *street = placemark.thoroughfare;
        NSString *city = placemark.locality;
        NSString *posCode = placemark.postalCode;
        NSString *country = placemark.country;

        NSLog("we live in %@", country);

        // stopping locationManager from fetching again
        [locationManager stopUpdatingLocation];
    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"failed to fetch current location : %@", error);
}

if you run your app through iphone simulator in XCODE, you need to set your desired location (coz simulator can't detect current location).