iOS Location Operations
Introduction
In iOS, location services are implemented via CoreLocation, enabling retrieval of the userβs current position as well as device movement information.
Step-by-step Example
- Create a simple View-based Application.
- Select your project file, then select the target, and add
CoreLocation.framework, as shown below:
- In
ViewController.xib, add two labels and create IBOutlets namedlatitudeLabelandlongitudeLabel. - Now select File β New β File... β, choose Objective-C class, and click Next.
- Set βSubclass ofβ to
NSObject, and name the classLocationHandler. - Click Create.
- Update
LocationHandler.has follows:
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@protocol LocationHandlerDelegate <NSObject>
@required
-(void) didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation;
@end
@interface LocationHandler : NSObject<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
}
@property(nonatomic,strong) id<LocationHandlerDelegate> delegate;
+(id)getSharedInstance;
-(void)startUpdating;
-(void) stopUpdating;
@end
- Update
LocationHandler.mas follows:
#import "LocationHandler.h"
static LocationHandler *DefaultManager = nil;
@interface LocationHandler()
-(void)initiate;
@end
@implementation LocationHandler
+(id)getSharedInstance
{
if (!DefaultManager)
{
DefaultManager = [[self allocWithZone:NULL]init];
;
}
return DefaultManager;
}
-(void)initiate
{
locationManager = [init];
locationManager.delegate = self;
}
-(void)startUpdating
{
;
}
-(void) stopUpdating
{
;
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if ([self.delegate respondsToSelector:@selector (didUpdateToLocation:fromLocation:)])
{
[self.delegate didUpdateToLocation:oldLocation fromLocation:newLocation];
}
}
@end
- Update
ViewController.has follows:
#import <UIKit/UIKit.h>
#import "LocationHandler.h"
@interface ViewController : UIViewController<LocationHandlerDelegate>
{
IBOutlet UILabel *latitudeLabel;
IBOutlet UILabel *longitudeLabel;
}
@end
- Update
ViewController.mas follows:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
;
[setDelegate:self];
[startUpdating];
}
- (void)didReceiveMemoryWarning
{
;
// Dispose of any resources that can be recreated.
}
-(void)didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[latitudeLabel setText:[NSString stringWithFormat: @"Latitude: %f",newLocation.coordinate.latitude]];
[longitudeLabel setText:[NSString stringWithFormat: @"Longitude: %f",newLocation.coordinate.longitude]];
}
@end
Output
When we run this application, the following output appears:
YouTip