articles

Home / DeveloperSection / Articles / Location Handling in iOS

Location Handling in iOS

Tarun Kumar2986 26-Oct-2015

In iOS, Core Location Framework provides a different type of classes that are used to find locations like GPS capability in our iPhone app. For example we want to create an travel app that locates the User's current location or to search nearby Offices, Schools or Colleges or Station or other place. The CoreLocationFramework provides the necessary interfaces in Objective-C for obtaining information about the user's location. 

Here we will build a simple app to show how we use Core Location framework, the

necessary things we will do are: 


     Creating a simple interface to display the GPS coordinate

      Learning to use CoreLocation api to retrieve the current location.

      Utilize the built-in api to translate the GPS coordinates into street address. (we

will learn about street address in another article).

 

To create Location handler app follow these steps: 


1.   In Xcode goto File > New > click on 'Project' > select 'Single View Application' and click on 'Next' button > enter Product Name as 'LocationHandler' and press 'Next' and after select location where you want to save the file and click 'Finish' button. 

2.   Now, select your project file > select TARGETS > under 'Linked Frameworks and Libraries' section click on '+' button > enter 'CoreLocation.framework' in search field, select it and press 'add' button. Now you can see the file is added in Navigation section. 

3.   Now, goto the Storyboard > add two labels for latitude and longitude and also for each label place a label in front of it and named it 'For Latitude value', 'For Longitude value'.

4.   Add a button under both labels and named it “My Location”.

5.   Now, connect the UI elements with our code using 'Assistant Editor' and ‘Hide the Utility Area’ for more space.

Location Handling in iOS 


6.    Now, press and hold 'Ctrl' key, click on 'For Latitude value' label and drag it on 'ViewController.h' file between @interface and @end keywords, now you see a prompt that allows to insert an outlet named it 'latitudeLabel'. Now repeat the same procedure a and create outlet for label 'For Longitude value'. Create an action method for 'Get My Location' button it will call when 'Touch Up Inside' event occurs. 

7.    After doing all of the things- ViewController.h file should look like this:

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutletUILabel *latitudeLabel;

@property (weak, nonatomic) IBOutletUILabel *longitudeLabel;

- (IBAction)getCurrentLocation:(id)sender;

@end

 

8.   Now, implement ‘CLLocationManagerDelegate’ protocol into ViewController.h file. (This protocol defines methods used to receive location and heading updates). 

9.   Before implementing ‘CLLocationManagerDelegate’, import <CoreLocation/CoreLocation.h> header file in ViewController.h file. After inserting the code look like this:

#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<CLLocationManagerDelegate>

 

10.  Now, goto ‘ViewController.m’ file and create an instance variable and named it as ‘locationManager’.

@implementation ViewController

{

    CLLocationManager *locationManager;

}

 

11.  ‘locationManager’ having object of ‘CLLocationManager’ that provides the location data. 

12.  Now, in ‘viewDidLoad’ method write the following code to instantiate the CLLocationManager object:

- (void)viewDidLoad

{

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    locationManager = [[CLLocationManageralloc] init];

}


Now, after creating the locationManager object you will able to use location service, it will send a stream of location data to our application continuously. 


13.  Now, write the following code in the ‘getCurrentLocation:’ method which is called when the ‘Get My Location’ button will clicked.


-(void)getCurrentLocation:(id)sender{

    locationManager.delegate = self;

    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [locationManagerstartUpdatingLocation];

}

location data is reported to our app through the location manager's associated delegate object, so we assign the 'ViewController' as the delegate object because all the location updates will be send to the delegate. To capture the location event we have to implement the delegate methods as defined in the protocol.

 

14.  Now, add the following code in the ViewController.m file:

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

{

    NSLog(@"didFailWithError: %@", error);

    UIAlertView *errorAlert = [[UIAlertViewalloc]

                                         initWithTitle:@"Error"

                                         message:@"Failed to Get Your Location"

                                         delegate:nil

                                         cancelButtonTitle:@"OK"otherButtonTitles:nil];

    [errorAlert show];

}

 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation

fromLocation:(CLLocation *)oldLocation {

    NSLog(@"didUpdateToLocation: %@", newLocation);

    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil) {

        longitudeLabel.text = [NSStringstringWithFormat:@"%.8f", currentLocation.coordinate.longitude];

        latitudeLabel.text = [NSStringstringWithFormat:@"%.8f", currentLocation.coordinate.latitude];

    }

}


15.  Now, our app is ready to run, but here is one thing to notice, can you know our computer does't have GPS.

Even if we assume that our computer have GPS but our Xcode would not able to use it.

Location Handling in iOS

16.  Now, after launching the application, click on “My Location” button. When we run app first time, an alert message will opened for requesting to access current location. Look like this:


Location Handling in iOS 


17.  Click on 'OK' button, otherwise our application will not be able to access location location. After clicking 'OK' button an Error alert message will be displayed because as we tell previously that our computer does't have any GPS system, so it is not able to access our current location. But we can set different types of locations. To verify is it true or not goto menu bar and select Debug > Location > here we can see the default location is set to “None”.


      Location Handling in iOS


So it is the reason of getting “Fail to Get Your Location” message.


Location Handling in iOS

18.  Now, we can also change the location from setting to “Apple” or “Apple Stores” or other from list. After setting the location, now our application is able to show the latitude and longitude values. Here we set "Apple": Look like this:


      Location Handling in iOS 

19.  Here is another way to simulate location in Xcode, when our app is running we can change the other location by using arrow button in the top bar of the debug area.

      Location Handling in iOS

 


Here is the complete code:

(no need to modify AppDelegate.h and AppDelegate.m file leave as it is)

 

ViewController.h file 

#import <UIKit/UIKit.h>

#import <CoreLocation/CoreLocation.h>

 

@interface ViewController : UIViewController<CLLocationManagerDelegate>

 

@property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;

@property (weak, nonatomic) IBOutlet UILabel *longitudeLabel;

- (IBAction)getCurrentLocation:(id)sender;

 

@end

ViewController.m file 

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController {

    CLLocationManager *locationManager;

}

@synthesize longitudeLabel,latitudeLabel;

- (void)viewDidLoad

{

    [super viewDidLoad];

         // Do any additional setup after loading the view, typically from a nib.

    locationManager = [[CLLocationManager alloc] init];

}

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

-(void)getCurrentLocation:(id)sender{

    locationManager.delegate = self;

    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];

}

 

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

{

    NSLog(@"didFailWithError: %@", error);

    UIAlertView *errorAlert = [[UIAlertView alloc]

                               initWithTitle:@"Error"

message:@"Failed to Get Your Location"

delegate:nil cancelButtonTitle:@"OK"

otherButtonTitles:nil];

    [errorAlert show];

}

 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation

fromLocation:(CLLocation *)oldLocation

{

    NSLog(@"didUpdateToLocation: %@", newLocation);

    CLLocation *currentLocation = newLocation;

   

    if (currentLocation != nil) {

        longitudeLabel.text = [NSStringstringWithFormat:@"%.8f", currentLocation.coordinate.longitude];

        latitudeLabel.text = [NSStringstringWithFormat:@"%.8f", currentLocation.coordinate.latitude];

    }

}

 

@end


Updated 07-Sep-2019

Leave Comment

Comments

Liked By