Skip to content

Instantly share code, notes, and snippets.

@CavalcanteLeo
Forked from chrishulbert/LocationHelper.m
Created March 22, 2016 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CavalcanteLeo/4f8305b743c970fd3419 to your computer and use it in GitHub Desktop.
Save CavalcanteLeo/4f8305b743c970fd3419 to your computer and use it in GitHub Desktop.
Blocks location helper for finding a very rough location on an iphone
//
// LocationHelper.m
//
// Created by Chris Hulbert on 24/04/12.
//
#import "LocationHelper.h"
@interface LocationHelper()
@property(copy) LocationBlock locationBlock;
@property(strong) CLLocationManager* locMan;
@end
@implementation LocationHelper
@synthesize locationBlock, locMan;
+ (void)getRoughLocation:(LocationBlock)block {
if ([CLLocationManager locationServicesEnabled]) {
// We have to instantiate something so we can use it as a delegate. Boo hiss. Blocks rule!
LocationHelper* lh = [[LocationHelper alloc] init];
lh.locationBlock = block;
// Kick off the location finder
lh.locMan = [[CLLocationManager alloc] init];
lh.locMan.desiredAccuracy = kCLLocationAccuracyThreeKilometers; // Get the roughest accuracy (eg use cell towers not gps)
lh.locMan.delegate = lh;
lh.locMan.purpose = locationHelperPurpose;
[lh.locMan startUpdatingLocation];
// This serves two purposes: keep the instance retained by the runloop, and timeout if things don't work
[lh performSelector:@selector(timeout) withObject:nil afterDelay:60];
} else {
block(nil); // Not enabled
}
}
// This is used to keep the instance retained by the runloop, and to call the block just in case the location manager didn't
- (void)timeout {
if (self.locationBlock) {
self.locationBlock(nil);
self.locationBlock=nil;
}
self.locMan = nil;
}
#pragma mark - Delegate stuff
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (self.locationBlock) {
self.locationBlock(newLocation);
self.locationBlock=nil;
}
self.locMan = nil;
}
// If it fails,
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"Location manager failed: %@", error);
if (self.locationBlock) {
self.locationBlock(nil);
self.locationBlock=nil;
}
self.locMan = nil;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment