Skip to content

Instantly share code, notes, and snippets.

@fayewest
Created October 15, 2012 22:54
Show Gist options
  • Save fayewest/3896169 to your computer and use it in GitHub Desktop.
Save fayewest/3896169 to your computer and use it in GitHub Desktop.
LocationHelper
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
typedef void (^ CallbackBlock)(float, float, NSError*);
@interface LocationHelper : NSObject <CLLocationManagerDelegate>
+ (LocationHelper*) instance;
- (void) getLocation:(CallbackBlock)block;
@end
#import "LocationHelper.h"
@interface LocationHelper ()
@property (nonatomic) CLLocationManager* locationManager;
@property (copy) CallbackBlock callback;
@property (nonatomic) float lat;
@property (nonatomic) float lng;
@end
@implementation LocationHelper
+ (LocationHelper*) instance {
static LocationHelper *instance;
@synchronized(self)
{
if (!instance)
instance = [[LocationHelper alloc] init];
return instance;
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
self.lat = newLocation.coordinate.latitude;
self.lng = newLocation.coordinate.longitude;
[manager stopUpdatingLocation];
self.callback(self.lat, self.lng, nil);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
self.callback(self.lat, self.lng, error);
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
switch (status) {
case kCLAuthorizationStatusDenied:
break;
case kCLAuthorizationStatusRestricted:
break;
default:
break;
}
}
- (void) getLocation:(CallbackBlock)block {
if (!self.locationManager) {
self.locationManager = [[CLLocationManager alloc] init];
}
self.locationManager.delegate = self;
self.callback = block;
[self.locationManager startUpdatingLocation];
}
@end
@GJNilsen
Copy link

Thanks for a great helper class! I love it!

I have this helper included in my AppDelegate with this code:

AppDelegate.h:
@Property (nonatomic, strong, readonly) CoreLocationHelper *coreLocationHelper;

  • (CoreLocationHelper *)clh;

AppDelegate.m:

  • (CoreLocationHelper *)clh
    {
    if (!_coreLocationHelper) {
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
    _coreLocationHelper = [CoreLocationHelper new];
    });
    }
    return _coreLocationHelper;
    }

And in my ViewController I access it like this:

CoreLocationHelper *clh = [(AppDelegate *)[[UIApplication sharedApplication] delegate] clh];
[clh getLocation:^(float latitude, float longitude, NSError *error){
if(&error){
NSLog(@"Uups %@",&error);
} else {
CLLocation *thisLocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
}
}];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment