Show Menu

Looking to hire an app developer?

Submit your 30 day Job Listing for FREE

xcode location tutorial

In this iPhone application development tutorial we are going to create an app which will present the user’s location info such as; geographical coordinates, altitude and speed using the CoreLocation Framework.

The CoreLocation Framework

From the early beginning of iOS, Apple gave to developers the ability to get user’s location using the CoreLocation Framework. However, the user must first allow an app to use location services in order to retrieve the user’s location.

permtask ios

Here is an app using location services which requests user’s permission in order to retrieve location.

Let’s get started!

First of all you need to create a new Xcode Single View Application:

xcode single view app

Then, click Next and you will be prompted to another screen asking you for the project settings. Type in the first field (“Product name”) the name of your project and click Next.

Importing the CoreLocation Framework

In order to use CoreLocation Framework you need to include the framework

  • Click on the Target
  • Click the “+” button on “Linked Frameworks and Libraries” section in order to access frameworks.
  • Finally click “Add”.
Import CoreLocation Framework
xcode choose framework

In order to use the CoreLocation framework you need to import it in the Xcode project application header file (in our case “ViewController.h”) as shown below:


#import 
@interface ViewController : UIViewController 

In our header file we should also declare some variables as shown below.

 
IBOutlet UILabel *latitude;
IBOutlet UILabel *longitude;
IBOutlet UILabel *altitude;
IBOutlet UILabel *speed;
CLLocationManager *locationManager;

locationManager is the object responsible for the location data. The UILabels are the controls on which we will show the location data.

Designing the screen

Now click on the “Main.storyboard” file and drag 8 UILabels on the view. Arrange the labels as shown in the picture below.

xcode storyboard view

When you arrange the UILabels properly, link each UILabel declared with the correspondent UILabel on the view as shown in the picture below.

xcode link file

Let’s get serious.

It is time to edit the implementation file (in our case “ViewController.m”).
Add the following code in the viewDidLoad method in order to instantiate and set locationManager properties.


- (void)viewDidLoad
{
    [super viewDidLoad];
    locationManager = [[CLLocationManager alloc]init]; // initializing locationManager
    locationManager.delegate = self; // we set the delegate of locationManager to self. 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; // setting the accuracy

    [locationManager startUpdatingLocation];  //requesting location updates
}

On the 4th line we instantiate the locationManager object which will be responsible for the location data.
On the 5th line we set the delegate of locationManager to ViewController (self) .
This means that every location related event will be sent to ViewController.
On the 6th line we set the desiredAccuracy to kCLLocationAccuracyBest which is the best provided. Keep in mind that higher accuracies need more device resources (power etc) and you should be careful on how you set the desiredAccuracy property.
Do not set the desiredAccuracy to more than you really need.

On the 8th line we call the startUpdating method of the locationManager.
By calling this method we request location updates.

In order to capture the location updates we have to implement the delegate methods of the locationManager properties.
Add the following code to ViewController.m file.


-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"There was an error retrieving your location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [errorAlert show];
    NSLog(@"Error: %@",error.description);
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *crnLoc = [locations lastObject];
    latitude.text = [NSString stringWithFormat:@"%.8f",crnLoc.coordinate.latitude];
    longitude.text = [NSString stringWithFormat:@"%.8f",crnLoc.coordinate.longitude];
    altitude.text = [NSString stringWithFormat:@"%.0f m",crnLoc.altitude];
    speed.text = [NSString stringWithFormat:@"%.1f m/s", crnLoc.speed];
}

The first method implemented (locationManager didFailWithError) will be called if the location manager face an error when it tries to retrieve location.

The second method implemented (and the most important one) will be called when the device has new location data. locationManage didUpdateLocations method provides an NSArray (locations) which contains the most recent locations (object of CLLocation type). So, the most recent location is the last object of the NSArray. We assign the value of the last location retrieved to a new CLLocation object called crnLoc and we set the text property of the UILabels to the location data we want.

Let’s run it!

Now run the application in the simulator. The app will first request your permission to use your current location then it will show you some fake location data on the UILabels.

You should see something like this:

xcode simulator app

Final Notes

I hope you find this tutorial helpful. If you have any question do not hesitate to ping me on Twitter or leave a comment below.

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


Written by:

I am 17 years old, student and amateur iOS app developer, computer and technology enthusiast. Check out my apps using the link provided and also use the other link to follow me on twitter

Comments

comments