O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.3. Pinpointing the Location of a Device

Problem

You want to find the latitude and longitude of a device.

Solution

Use the CLLocationManager class:

- (void)viewDidLoad {
    [super viewDidLoad];

    if ([CLLocationManager locationServicesEnabled]){
        self.myLocationManager = [[CLLocationManager alloc] init];
        self.myLocationManager.delegate = self;


        [self.myLocationManager startUpdatingLocation];
    } else {
        /* Location services are not enabled.
         Take appropriate action: for instance, prompt the
         user to enable the location services */
        NSLog(@"Location services are not enabled");
    }

}

In this code, myLocationManager is a property of type CLLocationManager. The current class is also the delegate of the location manager in this sample code.

Discussion

The Core Location framework in the SDK provides functionality for programmers to detect the current spatial location of an iOS device. Because in iOS, the user is allowed to disable location services using Settings, before instantiating an object of type CLLocationManager, it is best to first determine whether location services are enabled on the device.

Note

The delegate object of an instance of CLLocationManager must conform to the CLLocationManagerDelegate protocol.

This is how we will declare our location manager object in our view controller (the object creating an instance of CLLocationManager does not necessarily have to be a view controller):

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController () <CLLocationManagerDelegate ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required