Problem
You want to find the latitude and longitude of a device.
Solution
Use the CLLocationManager class:
#import "WSYViewController.h"
#import <MapKit/MapKit.h>
@interface WSYViewController
()<CLLocationManagerDelegate>
@property (nonatomic,strong)CLLocationManager *
myLocationManager;
@end
@implementation WSYViewController
-(void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
//we received the new loaction
NSLog(@"Latitude = %f ",[[locations
lastObject] coordinate].latitude);
NSLog(@"longitude = %f ",[[locations
lastObject] coordinate].longitude);
}
-(void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
NSLog(@"Failed to receive user‘s location
");
}
- (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");
}
}
@end
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.