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{[superviewDidLoad];if([CLLocationManagerlocationServicesEnabled]){self.myLocationManager=[[CLLocationManageralloc]init];self.myLocationManager.delegate=self;[self.myLocationManagerstartUpdatingLocation];}else{/* Location services are not enabled.Take appropriate action: for instance, prompt theuser 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>@interfaceViewController()<CLLocationManagerDelegate ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access