Block-based wrapper around Core Location
#import <Foundation/Foundation.h> | |
#import <CoreLocation/CoreLocation.h> | |
typedef void (^JWLocationManagerCallback)(CLLocation *location); | |
typedef void (^JWLocationManagerErrorCallback)(NSError *error); | |
@interface JWLocationManager : NSObject <CLLocationManagerDelegate> | |
@property (nonatomic, copy) NSString *purpose; | |
@property (nonatomic, copy) JWLocationManagerCallback locationUpdatedBlock; | |
@property (nonatomic, copy) JWLocationManagerErrorCallback locationErrorBlock; | |
+ (JWLocationManager *)sharedInstance; | |
- (void)startUpdatingLocation; | |
- (void)disableLocationManager; | |
@end |
#import "JWLocationManager.h" | |
@interface JWLocationManager() | |
@property (nonatomic, strong) CLLocationManager *locationManager; | |
@property (nonatomic, strong) CLLocation *currentLocation; | |
@end | |
@implementation JWLocationManager | |
@synthesize locationManager = _locationManager; | |
@synthesize locationErrorBlock = _locationErrorBlock; | |
@synthesize locationUpdatedBlock = _locationUpdatedBlock; | |
static JWLocationManager *sharedManager = nil; | |
+ (JWLocationManager *)sharedInstance { | |
if (!sharedManager) | |
sharedManager = [[self alloc] init]; | |
return sharedManager; | |
} | |
- (id)init { | |
self = [super init]; | |
if (!self) return nil; | |
self.locationManager = [[CLLocationManager alloc] init]; | |
self.locationManager.delegate = self; | |
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer; | |
return self; | |
} | |
- (void)setPurpose:(NSString *)purpose { | |
_purpose = [purpose copy]; | |
self.locationManager.purpose = purpose; | |
} | |
- (void)startUpdatingLocation { | |
[self.locationManager startUpdatingLocation]; | |
} | |
- (void)disableLocationManager { | |
[self.locationManager stopUpdatingLocation]; | |
self.locationManager = nil; | |
self.currentLocation = nil; | |
self.locationErrorBlock = nil; | |
self.locationUpdatedBlock = nil; | |
sharedManager = nil; | |
} | |
- (void)locationManager:(CLLocationManager *)manager | |
didUpdateToLocation:(CLLocation *)newLocation | |
fromLocation:(CLLocation *)oldLocation { | |
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; | |
if (locationAge > 5.0) return; | |
if (newLocation.horizontalAccuracy < 0) return; | |
self.currentLocation = newLocation; | |
if (self.locationUpdatedBlock) | |
self.locationUpdatedBlock(newLocation); | |
[self.locationManager stopUpdatingLocation]; | |
} | |
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { | |
[self.locationManager stopUpdatingLocation]; | |
if (self.locationErrorBlock) | |
self.locationErrorBlock(error); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment