Get Current Location With Core Location

The Core Location framework can be used to create location-aware applications. The Core Location framework uses the device’s internal hardware to determine the current location. In this tutorial we will get the current user location and display the latitude and longtitude. 

Open Xcode and create a new Single View Application. For product name, use iOS7CurrentLocationTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices.

Go to the Storyboard and drag two labels to the main View. Give them a title of "Latitude and "Longtitude". Next, drag two more labels to the main view and give them a title of "0.0". The storyboard should look like this.

Select the Assistant Editor and open ViewController.m. Ctrl and drag from the topright label  to the @interface section and create the following outlet

Repeat for the bottom right label

The coreLocation framework makes it possible to work with location-based application, so let's import the coreLocation header first.

#import <CoreLocation/CoreLocation.h>

Add the following property 

@property (nonatomic,strong) CLLocationManager *locationManager;

The CLLocationManager class handles the location events for your application. We also need to conform our view controller to the CLLocationMangerDelegate protocol so change the @interface line into

@interface ViewController () <CLLocationManagerDelegate>

Next change the viewDidLoad method 

- (void)viewDidLoad
[super viewDidLoad];

if ([CLLocationManager locationServicesEnabled]) {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
} else {
NSLog(@"Location services are not enabled");

First we check if the Location Services are enabled on the device and if so the locationManager class is initialised and the startUpdatingLocation method is called. This method will call the locationManagerdidUpdateLocation method

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
CLLocation *location = [locations lastObject];
self.latitudeValue.text = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
self.longtitudeValue.text = [NSString stringWithFormat:@"%f", location.coordinate.longitude];

The Device Location is assigned to a CLLocation object. From this object we can extract the latitude and longtitude and write them to our labels. Build and Run, you will see the current coordinates of the device displayed on the screen.

You can download the source code of the iOS7CurrentLocationTutorial at the ioscreator repository on github.