6.3. Pinpointing the Location of a Device
Problem
You want to find the latitude and longitude of a device.
Solution
Use the CLLocationManager
class:
if ([CLLocationManager locationServicesEnabled]){ self.myLocationManager = [[CLLocationManager alloc] init]; self.myLocationManager.delegate = self; self.myLocationManager.purpose = @"To provide functionality based on user's current location."; [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 the Settings, before instantiating an object
of type CLLocationManager
, it is
best to first determine whether the 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 the
.h file of a view controller (the
object creating an instance of CLLocationManager
does not necessarily have
to be a view controller):
#import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> ...
Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.